Fetch ошибка 403

Below code is not working and returning 403 forbidden but the same url giving the correct response postman tool.

fetch('https://example.com/', {
  method: 'POST',
  headers: {'Content-Type': 'application/json', },
 body:JSON.stringify(sampledata),
}).then(result => console.log('success====:', result))
  .catch(error => console.log('error============:', error));

asked Aug 8, 2017 at 19:04

Manu Ram V's user avatar

4

You need to add credentials: ‘include’ to your request.

fetch('https://example.com/', {
      credentials: 'include',
      method: 'POST',
      headers: {'Content-Type': 'application/json', },
      body: JSON.stringify(sampledata),

      }).then(result => console.log('success====:', result))
        .catch(error => console.log('error============:', error));

answered May 17, 2018 at 9:50

Pauli's user avatar

PauliPauli

1494 silver badges13 bronze badges

1

Please read this article Cross-Origin Resource Sharing , And change your API «Content-Type» to «text/plain». It will work (both fetch and axios)

fetch('https://example.com/', {
  method: 'POST',
  headers: {'Content-Type': 'text/plain', },
 body:JSON.stringify(sampledata),
}).then(result => console.log('success====:', result))
  .catch(error => console.log('error============:', error));

answered Jun 19, 2018 at 12:01

Sujith S's user avatar

Sujith SSujith S

5555 silver badges8 bronze badges

Probably CORS problem. Regular web pages can send and receive data from remote servers, but they’re limited by the same origin policy. Extensions like postman aren’t. You have to configure CORS on your backend.

answered Aug 8, 2017 at 20:22

mradziwon's user avatar

mradziwonmradziwon

1,2061 gold badge9 silver badges13 bronze badges

This is because Postman doesn’t need to abide by access-control-allow-origin headers. Browser vendors look for this header from host server. If the server contains ACCESS-CONTROL-ALLOW-ORIGIN: "*" and Access-Control-Allow-Methods: "GET, POST, PUT, DELETE, OPTIONS" this would then tell the browser that this resource has given permission to be accessed.

John Conde's user avatar

John Conde

218k99 gold badges455 silver badges496 bronze badges

answered Feb 26, 2021 at 20:34

Clinton Jones's user avatar

Catch Status Code 403 In Fetch With Code Examples

Hello everyone, in this post we will look at how to solve Catch Status Code 403 In Fetch in programming.

let response = await fetch(url1);
		console.log(response.status);
		if (response.status == 200) {
			let resJSON = await response.json();
			console.log(resJSON);
            let data=resJSON;
		} else {
			console.log("ERROR");
		}

By investigating a variety of use scenarios, we were able to demonstrate how to solve the Catch Status Code 403 In Fetch problem that was present.

How do I get 403 error on Fetch?

catch status code 403 in fetch

  • let response = await fetch(url1);
  • console. log(response. status);
  • if (response. status == 200) {
  • let resJSON = await response. json();
  • console. log(resJSON);
  • let data=resJSON;
  • } else {
  • console. log(«ERROR»);

How do I fix status code 403?

How to Fix the 403 Forbidden Error

  • Check the . htaccess File.
  • Reset File and Directory Permissions.
  • Disable WordPress Plugins.
  • Upload an Index Page.
  • Edit File Ownership.
  • Verify the A Record.
  • Scan for Malware.
  • Clear Your Web History/Cache.

How do you handle errors in Fetch?

The fetch() function will automatically throw an error for network errors but not for HTTP errors such as 4xx or 5xx responses. For HTTP errors we can check the response. ok property to see if the request failed and reject the promise ourselves by calling return Promise.09-Oct-2021

Why do I keep seeing 403 Forbidden?

The HTTP 403 Forbidden response status code indicates that the server understands the request but refuses to authorize it. This status is similar to 401 , but for the 403 Forbidden status code re-authenticating makes no difference.08-Sept-2022

What is failed fetch error?

The «TypeError: Failed to fetch» occurs for multiple reasons: An incorrect or incomplete URL has been passed to the fetch() method. The server you are making a request to does not send back the correct CORS headers. A wrong protocol is specified in the url.25-Jul-2022

Does fetch get by default?

So coming to fetch, it takes two arguments, the “URL” and an object, “options”. Only the ‘URL’ is mandatory, and the method is set to GET by default if not provided.

Can you bypass a 403 error?

How to Bypass 403 restrictions? There are many headers and paths which you can use to bypass 403 restrictions. Adding Headers in request :By adding different headers in request with value 127.0. 0.1 can also help in bypassing restrictions.03-Oct-2021

What area code is 403 from?

Calgary

How do I fix a 403 error in Chrome?

Refreshing the page is always worth a shot. Many times the 403 error is temporary, and a simple refresh might do the trick. Most browsers use Ctrl+R on Windows or Cmd+R on Mac to refresh, and also provide a Refresh button somewhere on the address bar.24-Jan-2022

How do you handle responses in fetch API?

The Fetch API allows you to asynchronously request for a resource. Use the fetch() method to return a promise that resolves into a Response object. To get the actual data, you call one of the methods of the Response object e.g., text() or json() . These methods resolve into the actual data.

Overview

  • **Client ID: zWLhTbc_Q0R2800Q5EPSKw
  • **Issue type: Question
  • **Summary: Making a get call from javascript using fetch and the new API KEY, but receiving a 403 error.
  • **Platform: Web

Description

Using the below call in javascript with my actual API Key substituted in from my own website, I am receiving a 403 error. Is there anything wrong with my request that would be causing the error?

Endpoint

Fusion Search API

Parameters or Sample Request

fetch(`https://api.yelp.com/v3/businesses/search?latitude=${lat}&longitude=${lng}`, {
  headers: {
    Authorization: 'Bearer <API_KEY>'
  }
}).then(function(response) {
  debugger;
}).catch(function(err) {
  console.log(err);
});

Response

HTTP403: FORBIDDEN — The server understood the request, but is refusing to fulfill it.
(Fetch)OPTIONS — https://api.yelp.com/v3/businesses/search?latitude=44.50326189999999&longitude=-88.06424670000001

This is a quick example of how to automatically logout of a React app if a fetch request returns a 401 Unauthorized or 403 Forbidden response.

The code snippets in this tutorial are from a React + Recoil Login tutorial I posted recently, to see the code running in a live demo app check out React + Recoil — User Registration and Login Example & Tutorial.

Recoil is used in the example to store the current authenticated user in the auth shared state object, but Recoil isn’t required if your React app uses another way to store the user’s logged in state such as Redux or RxJS etc, the only requirement is that you can get and set the user’s logged in state.

Fetch Wrapper with Logout on 401 or 403

Path: /src/_helpers/fetch-wrapper.js

The fetch wrapper is a lightweight wrapper around the native browser fetch() function used to simplify the code for making HTTP requests by automatically handling request errors, parsing JSON response data and setting the HTTP auth header. It returns an object with methods for making get, post, put and delete requests.

The handleResponse() function checks if there is an HTTP error in the response (!response.ok), if there is an error and the response status code (response.status) is 401 or 403 the user is logged out of the React app and redirected to the login page.

With the fetch wrapper a POST request can be made as simply as this: fetchWrapper.post(url, body);. It’s called in the example app by user actions.

import { useRecoilState } from 'recoil';

import { history } from '_helpers';
import { authAtom } from '_state';
import { useAlertActions } from '_actions';

export { useFetchWrapper };

function useFetchWrapper() {
    const [auth, setAuth] = useRecoilState(authAtom);
    const alertActions = useAlertActions();

    return {
        get: request('GET'),
        post: request('POST'),
        put: request('PUT'),
        delete: request('DELETE')
    };

    function request(method) {
        return (url, body) => {
            const requestOptions = {
                method,
                headers: authHeader(url)
            };
            if (body) {
                requestOptions.headers['Content-Type'] = 'application/json';
                requestOptions.body = JSON.stringify(body);
            }
            return fetch(url, requestOptions).then(handleResponse);
        }
    }
    
    // helper functions
    
    function authHeader(url) {
        // return auth header with jwt if user is logged in and request is to the api url
        const token = auth?.token;
        const isLoggedIn = !!token;
        const isApiUrl = url.startsWith(process.env.REACT_APP_API_URL);
        if (isLoggedIn && isApiUrl) {
            return { Authorization: `Bearer ${token}` };
        } else {
            return {};
        }
    }
    
    function handleResponse(response) {
        return response.text().then(text => {
            const data = text && JSON.parse(text);
            
            if (!response.ok) {
                if ([401, 403].includes(response.status) && auth?.token) {
                    // auto logout if 401 Unauthorized or 403 Forbidden response returned from api
                    localStorage.removeItem('user');
                    setAuth(null);
                    history.push('/account/login');
                }
    
                const error = (data && data.message) || response.statusText;
                alertActions.error(error);
                return Promise.reject(error);
            }
    
            return data;
        });
    }    
}

User Actions

Path: /src/_actions/user.actions.js

The user actions object returned by the useUserActions() hook function contains methods for user registration, authentication and CRUD operations. It handles communication between the React app and the backend api for everything related to users, and also handles Recoil state update operations for users and auth atoms. HTTP requests to the API are sent with the fetch wrapper.

I included it here to show examples of the fetchWrapper being called to make HTTP requests to the API from the React app.

import { useRecoilState, useSetRecoilState, useResetRecoilState } from 'recoil';

import { history, useFetchWrapper } from '_helpers';
import { authAtom, usersAtom, userAtom } from '_state';

export { useUserActions };

function useUserActions () {
    const baseUrl = `${process.env.REACT_APP_API_URL}/users`;
    const fetchWrapper = useFetchWrapper();
    const [auth, setAuth] = useRecoilState(authAtom);
    const setUsers = useSetRecoilState(usersAtom);
    const setUser = useSetRecoilState(userAtom);

    return {
        login,
        logout,
        register,
        getAll,
        getById,
        update,
        delete: _delete,
        resetUsers: useResetRecoilState(usersAtom),
        resetUser: useResetRecoilState(userAtom)
    }

    function login({ username, password }) {
        return fetchWrapper.post(`${baseUrl}/authenticate`, { username, password })
            .then(user => {
                // store user details and jwt token in local storage to keep user logged in between page refreshes
                localStorage.setItem('user', JSON.stringify(user));
                setAuth(user);

                // get return url from location state or default to home page
                const { from } = history.location.state || { from: { pathname: '/' } };
                history.push(from);
            });
    }

    function logout() {
        // remove user from local storage, set auth state to null and redirect to login page
        localStorage.removeItem('user');
        setAuth(null);
        history.push('/account/login');
    }

    function register(user) {
        return fetchWrapper.post(`${baseUrl}/register`, user);
    }

    function getAll() {
        return fetchWrapper.get(baseUrl).then(setUsers);
    }

    function getById(id) {
        return fetchWrapper.get(`${baseUrl}/${id}`).then(setUser);
    }

    function update(id, params) {
        return fetchWrapper.put(`${baseUrl}/${id}`, params)
            .then(x => {
                // update stored user if the logged in user updated their own record
                if (id === auth?.id) {
                    // update local storage
                    const user = { ...auth, ...params };
                    localStorage.setItem('user', JSON.stringify(user));

                    // update auth user in recoil state
                    setAuth(user);
                }
                return x;
            });
    }

    // prefixed with underscored because delete is a reserved word in javascript
    function _delete(id) {
        setUsers(users => users.map(x => {
            // add isDeleting prop to user being deleted
            if (x.id === id) 
                return { ...x, isDeleting: true };

            return x;
        }));

        return fetchWrapper.delete(`${baseUrl}/${id}`)
            .then(() => {
                // remove user from list after deleting
                setUsers(users => users.filter(x => x.id !== id));

                // auto logout if the logged in user deleted their own record
                if (id === auth?.id) {
                    logout();
                }
            });
    }
}

My wife and I are attempting to ride motorcycles around Australia and vlog about it on YouTube.

You can get a request digest by sending a POST request to

http://server/site/_api/contextinfo

with only an accept: 'application/json;odata=verbose' header.


Apparently there is some confusion about what I am saying.

When SharePoint generates a page, it adds a hidden element with the ID __REQUESTDIGEST. Usually, when you are writing code to call the REST API, and that code is hosted on a page served by SharePoint, you use

document.getElementById('__REQUESTDIGEST').value

in order to get the value of the request digest, so that you can then use it as the value of the X-RequestDigest header in your REST call.

If your code is not running on a page served by SharePoint, that hidden element will of course not be there, so trying to do

document.getElementById('__REQUESTDIGEST').value

will not work.

HOWEVER, there is another way to get that value. Now, I’ve never used the Headers object, but following the pattern of OP’s code sample, if you do this:

const url = 'http://sp2016:5155/_api/contextinfo';

const requestDigestPostSettings = {
    method: 'POST',
    headers: new Headers({
        'accept': 'application/json;odata=verbose'
    })
}

fetch(url, requestDigestPostSettings).then(response => {

    const requestDigestValue = response.d.GetContextWebInformation.FormDigestValue;

    // now you can use the requestDigestValue in the X-RequestDigest header in your _next_ REST call
});

NOTE: I just tested this through Postman on a SP2013 site. It seems that OP is using SP2016? So I’m not sure if the exact structure of the response object will be d.GetContextWebInformation.FormDigestValue, but the digest value will be in the response somewhere.

The point being that you can get a request digest value by making a REST call to the site if you cannot get it through document.getElementById, which you can then turn around and use in the X-RequestDigest header of a subsequent REST call where you do what you are really trying to do in the first place.

Понравилась статья? Поделить с друзьями:
  • Ferrum ошибка e01
  • Fetch first git ошибка
  • Fetch completed 1с код ошибки 4
  • Feststellbremse einlegen ошибка ман
  • Ferrum кондиционеры коды ошибок