npm start 得到 401 并且节点 app.js 得到 200 响应

npm start gets 401 and node app.js gets 200 response

我有一个 React 项目,我 运行 使用 npm start 并且这段代码从第二次获取中得到 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)});
})

Buffer - 未在浏览器中显示 javascript。

而不是

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

仅使用

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

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

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