[英]How do you make an API request using browser fetch with token auth
我正在尝试使用fetch(browser)发出API请求。 标头中需要令牌才能发出请求。
我可以在节点(服务器端)中成功发出请求。 但是,在浏览器上发出请求时, OPTIONS
请求失败并显示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)
})
我收到的错误是"NetworkError when attempting to fetch resource."
出现"NetworkError when attempting to fetch resource."
要在浏览器上正常运行,应采用什么正确的配置?
您没有正确发送标题。 尝试这个。
myHeaders = new Headers({
'Authorization': 'Token ' + process.env.API_TOKEN,
'Content-Type': 'application/x-www-form-urlencoded'
});
接着
fetch(order_url, {
headers: myHeaders,
method: 'GET'
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.