【问题标题】:React & Node.js fetch basic authorizationReact 和 Node.js 获取基本授权
【发布时间】:2020-12-05 14:15:23
【问题描述】:

我正在使用 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
  }

});

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

访问 'http://127.0.0.1:5000/' 从源获取 “http://localhost:3000”已被 CORS 策略阻止:响应 预检请求未通过访问控制检查:它没有 HTTP 正常状态。

但是,当我在第二个中间件 if (username === auth.username && password === auth.password) 中评论比较部分时,它工作正常。我尝试使用 Postman 发送请求也没有问题发生。仅当我从反应应用程序发出请求时才会出现问题。有谁知道是什么原因?非常感谢

【问题讨论】:

  • 你使用 CORD npm 吗?
  • 我没有使用 cors。

标签: node.js reactjs express fetch


【解决方案1】:

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

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

more information about CORS npm

【讨论】:

    猜你喜欢
    • 2022-07-20
    • 2021-10-17
    • 1970-01-01
    • 1970-01-01
    • 2020-12-28
    • 1970-01-01
    • 2019-10-04
    • 1970-01-01
    • 2012-03-12
    相关资源
    最近更新 更多