提问者:小点点

React&node.js获取基本授权


我正在使用fetch api从reactjs向Node.js后端发出请求,使用下面的代码进行基本授权。。。

反应

fetch(baseUrl, {
  method: 'get',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
    authorization: 'Basic ' + secret,
  },
}).then((res) => {
  if (res.ok) {
    return res.json();
  } else {
    return Promise.reject(res.statusText);
  }
})
  .then((resBody) => {
    //
  })
  .catch((error) => {
    console.error(error);
  });

node.js

app.use((req, res, next) => {

  res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');

  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

  res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Authorization');

  res.setHeader('Access-Control-Allow-Credentials', true);

  return next();
});

app.use((req, res, next) => {

  const base64Credentials = (req.headers.authorization || '').split(' ')[1] || '';

  const [username, password] = Buffer.from(base64Credentials, 'base64').toString().split(':');

  const auth = { username: 'username', password: '123456' }
  console.log(username, password, auth.username, auth.password);
  // comment below
  if (username === auth.username && password === auth.password) {
    return next();
  } else {
    res.status(401).send('Authentication required.'); // custom message
  }

});

当我尝试发出请求时发生以下错误。

CORS策略阻止了从源“HTTP://localhost:3000”获取“HTTP://127.0.0.1:5000/”的访问:对预飞行请求的响应没有通过访问控制检查:它没有HTTP ok状态。

但是,当我在第二个中间件中注释比较部分if(username===auth.username&password===auth.password)时,它可以正常工作。我试过用邮递员发送请求,也没有问题发生。只有当我从react应用程序发出请求时,才会出现这个问题。有人知道原因是什么吗?多谢


共1个答案

匿名用户

CORS npm似乎没有安装npm i CORS,编写以下代码:

var express = require('express')
var cors = require('cors')
var app = express()
 
app.use(cors())

有关CORS npm的详细信息