使用 Basic Auth 获取 ReactJS 返回 401(未授权).预检请求未通过访问控制检查

我是 ReactJS 的新手,但我现在正在尝试自学.当我尝试在我的带有 MongoDB 的 RestAPI 中使用我的 Web 应用程序上的 fetch 函数添加数据时,我遇到了一个问题.当我点击我的按钮时,它会运行以下代码:

I'm new at ReactJS but I'm trying to learn by myself now. I'm facing a problem when I try to add data do may Database, in my RestAPI with MongoDB, using fetch function on my web Application. When I click my button, it runs the following code:

SubmitClick(){
    //console.log('load Get User page'); //debug only

    fetch('http://localhost:4000/users/', {
      method: 'POST',
      headers: {
        'Authorization': 'Basic YWRtaW46c3VwZXJzZWNyZXQ=',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        email: 'deadpool@gmail.com',
        first_name: 'Wade',
        last_name: 'Wilson',
        personal_phone: '(11) 91111-2222',
        password: 'wolv3Rine'
      })
    })

    //this.props.history.push('/get'); //change page layout and URL
}

我在浏览器上收到以下消息:

and I get the following message on my browser:

选项 http://localhost:4000/users/ 401(未授权)

OPTIONS http://localhost:4000/users/ 401 (Unauthorized)

未能加载 http://localhost:4000/users/:对预检请求的响应没有t 通过访问控制检查:请求的资源上不存在Access-Control-Allow-Origin"标头.因此,Origin 'http://localhost:3000' 是不允许访问的.响应的 HTTP 状态代码为 401.如果不透明的响应满足您的需求,请将请求的模式设置为no-cors"以获取禁用 CORS 的资源.

Failed to load http://localhost:4000/users/: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 401. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Uncaught (in promise) TypeError: Failed to fetch

Uncaught (in promise) TypeError: Failed to fetch

我的 RestAPI 具有基本身份验证,但我不知道应该在标题中插入什么才能访问.当我配置授权"选项卡时,我从邮递员那里得到了这个 'Authorization': 'Basic YWRtaW46c3VwZXJzZWNyZXQ=', ,它被自动添加到标题中.

My RestAPI have Basic Auth, but i don't know what i'm supposed to insert in headers to have access. I got this 'Authorization': 'Basic YWRtaW46c3VwZXJzZWNyZXQ=', from Postman, when I configured the Authorization tab, and it was automatically added to the headers.

我使用谷歌浏览器作为我的默认浏览器.

I'm using Google Chrome as my default browser.

我的后端代码如下:

const express =     require('express');
const bodyParser =  require('body-parser');
const mongoose =    require('mongoose');
var basicAuth =     require('express-basic-auth')

const app = express();

mongoose.connect('mongodb://localhost/usersregs', { useMongoClient: true });
mongoose.Promise = global.Promise;

app.use(basicAuth({
    users: {
        'admin': 'supersecret',
        'adam': 'password1234',
        'eve': 'asdfghjkl'
    }
}))

app.use(bodyParser.json());

app.use(function(err, req, res, next){
    console.log(err);
    //res.status(450).send({err: err.message})
});

app.use(require('./routes/api'));  

app.listen(4000, function(){
    console.log('Now listening for request at port 4000');
}); 

推荐答案

您正在尝试从端口 3000(您的客户端)访问端口 4000(您的 API 或后端).这违反了同源政策,即使您显然是在同一台机器上同时运行客户端和 API.

You're trying to access port 4000 (your API, or backend) from port 3000 (Your client). This violates the Same-origin policy, even though you're clearly running both the client and the API from the same machine.

要解决这个问题,最简单的方法是从与您的 API 相同的端口(端口 4000)启动您的客户端,这应该允许您的主机看到您正在尝试从同一个域/端口访问资源不会强制进行预检请求.

To get around this the easiest way is to just fire up your client from the same port as your API (port 4000) this should allow your host to see that you're trying to access resources from the same domain/port which won't force a preflight request.

如果这不可能,您将不得不配置 CORS对于您的 API,并且此问题未提供有关后端的任何详细信息,因此我目前无法指导您如何执行此操作.

If that's not possible you'll have to configure CORS for your API, and this question doesn't give any details about the backend so I can't instruct you on how to do that at the moment.

当然,如果您在生产中运行两台单独的服务器,这种方法显然是行不通的,但这可能超出了这个问题的范围.

And of course this approach obviously won't work if you're running two separate servers in production, but that's probably outside of the scope of this question.

相关文章