简体   繁体   English

如何使用带有令牌身份验证的浏览器提取来发出API请求

[英]How do you make an API request using browser fetch with token auth

I'm trying to make an API request using fetch(browser). 我正在尝试使用fetch(browser)发出API请求。 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. 但是,在浏览器上发出请求时, 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)
  })

The error i receive is "NetworkError when attempting to fetch resource." 我收到的错误是"NetworkError when attempting to fetch resource."出现"NetworkError when attempting to fetch resource." What would be the correct configuration for this to work on the browser? 要在浏览器上正常运行,应采用什么正确的配置?

You 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'
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM