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
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
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 SSujith S
5455 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
mradziwonmradziwon
1,1661 gold badge8 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
217k99 gold badges455 silver badges496 bronze badges
answered Feb 26, 2021 at 20:34
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
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.
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();
}
});
}
}
Subscribe to my YouTube channel or follow me on Twitter, Facebook or GitHub to be notified when I post new content.
I’m currently attempting to travel around Australia by motorcycle with my wife Tina on a pair of Royal Enfield Himalayans. You can follow our adventures on YouTube, Instagram and Facebook.
Написал скрипт в котором асинхронная функция fetch-запросом получает от API Яндекс диска ответ в виде json, который в дальнейшем используется для перемещения по директориям и воспроизведения аудио-файлов в них. Но проблема в том, что аудио не воспроизводится… при запросе 403 ошибка. Не понимаю, что я сделал не так?
Для примера можно зайти в директорию Семейные пары
jsfiddle.net
-
Вопрос задан08 июн. 2022
-
347 просмотров
Оказывается, yandex почему-то возвращает 403, если в заголовках запроса есть параметр Referrer. Помогло добавить в html страницы:
<meta name="referrer" content="no-referrer">
После этого Referrer из запросов исчез, и всё заработало.
Пригласить эксперта
-
Показать ещё
Загружается…
04 июн. 2023, в 01:35
1500 руб./за проект
04 июн. 2023, в 01:25
40000 руб./за проект
03 июн. 2023, в 23:42
1500 руб./за проект