【问题标题】:npm start gets 401 and node app.js gets 200 responsenpm start 得到 401 并且 node app.js 得到 200 响应
【发布时间】:2020-04-05 22:00:27
【问题描述】:

我有一个使用 npm start 运行的 React 项目,此代码从第二次获取中得到 401 错误(第一次正常)。它运行良好,仅使用节点返回 200,就像在“node App.js”中一样。

那么我需要做什么才能运行我的 React 项目并获得 200 响应?为什么 npm 和 node 对这个请求响应会有这种差异?

const clientID = <ClientID>
const clientSecret = <ClientSecret>
const encode = Buffer.from(`${clientID}:${clientSecret}`, 'utf8').toString('base64')

const requestOptions = {
    method: 'POST',
    headers: {  'Content-Type': 'application/x-www-form-urlencoded',
                'Authorization': `Basic ${encode}`,
            },
};

fetch("https://auth-nato.auth.us-east-1.amazoncognito.com/oauth2/token?grant_type=client_credentials", requestOptions)
.then(response => { return response.json() })
.then(data => { 
  const requestOptions2 = {
    method: 'POST',
    mode: 'no-cors',
    headers: {  'Content-Type': 'application/json',
                'Authorization': `Bearer ${data.access_token}`
            },
    body: '{"username":"Ana", "password":"test123","user_id":"ana@email.com"}'
  };
  fetch('https://j1r07lanr6.execute-api.sa-east-1.amazonaws.com/v1/register', requestOptions2)
  .then(response => {console.log(response)});
})

【问题讨论】:

    标签: javascript node.js amazon-web-services fetch-api http-status-code-401


    【解决方案1】:

    Buffer - 不在浏览器的 javascript 中显示。

    代替

    const encode = Buffer.from(`${clientID}:${clientSecret}`, 'utf8').toString('base64')
    

    只使用

    const encode = btoa(`${clientID}:${clientSecret}`);
    

    MDN 上阅读有关 base64 编码的更多信息。

    【讨论】:

      【解决方案2】:

      我发现这是一个需要在后端正确设置的 CORS 问题。我的解决方法是禁用 chrome 网络安全并删除“mode: no-cors”。 我尝试将 "Access-Control-Allow-Origin":"http://localhost:3000" 添加到标题中,但它不起作用。

      【讨论】:

        猜你喜欢
        • 2023-02-01
        • 1970-01-01
        • 2018-06-29
        • 2020-04-28
        • 2023-04-08
        • 1970-01-01
        • 1970-01-01
        • 2020-02-09
        • 2019-04-24
        相关资源
        最近更新 更多