I'm trying to make an API request using fetch(browser). A token is required in the headers to make the request.
I can make successful requests in node (server side).
However, when making requests on the browser, the OPTIONS
request fails with 401.
const order_url = new URL(process.env.API_URL + 'orders/');
const params = { type: 'amazon', status: 'in_queue' };
Object.keys(params).forEach(key => url.searchParams.append(key, params[key]));
const headers = {
Authorization: 'Token ' + process.env.API_TOKEN,
'Content-Type': 'application/x-www-form-urlencoded'
};
fetch(order_url, {
headers
})
.then(response => response.json())
.then(result => {
console.log(result);
})
.catch(error => {
console.error(error)
})
The error i receive is "NetworkError when attempting to fetch resource."
What would be the correct configuration for this to work on the browser?
I'm trying to make an API request using fetch(browser). A token is required in the headers to make the request.
I can make successful requests in node (server side).
However, when making requests on the browser, the OPTIONS
request fails with 401.
const order_url = new URL(process.env.API_URL + 'orders/');
const params = { type: 'amazon', status: 'in_queue' };
Object.keys(params).forEach(key => url.searchParams.append(key, params[key]));
const headers = {
Authorization: 'Token ' + process.env.API_TOKEN,
'Content-Type': 'application/x-www-form-urlencoded'
};
fetch(order_url, {
headers
})
.then(response => response.json())
.then(result => {
console.log(result);
})
.catch(error => {
console.error(error)
})
The error i receive is "NetworkError when attempting to fetch resource."
What would be the correct configuration for this to work on the browser?
- Is this node environment? – kockburn Commented Jan 20, 2019 at 21:55
- 1 Is the api CORS enabled? – charlietfl Commented Jan 20, 2019 at 22:08
- This is the browser environment and CORS is enabled in the API. – Duncan Gichimu Commented Jan 20, 2019 at 22:11
-
2
@DuncanGichimu is this a bearer token? If so, you need the bearer header like so:
'Authorization': 'Bearer ' + process.env.API_TOKEN,
– Ben Commented Jan 20, 2019 at 22:14 - @kemicofa I've tried this in the node environment and it works. I will restate my question. – Duncan Gichimu Commented Jan 20, 2019 at 22:14
1 Answer
Reset to default 2You are not sending headers properly. Try this.
myHeaders = new Headers({
'Authorization': 'Token ' + process.env.API_TOKEN,
'Content-Type': 'application/x-www-form-urlencoded'
});
and then
fetch(order_url, {
headers: myHeaders,
method: 'GET'
})
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744831564a4596114.html
评论列表(0条)