在ReactJS中使用基本身份验证返回401(未经授权)进行抓取.飞行前请求未通过访问控制检查 [英] Fetch in ReactJS with Basic Auth return 401 (Unauthorized). Preflight request doesn't pass access control check

查看:93
本文介绍了在ReactJS中使用基本身份验证返回401(未经授权)进行抓取.飞行前请求未通过访问控制检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是ReactJS的新手,但现在我想自己学习.当我尝试在Web应用程序上使用fetch函数在我的RestAPI和MongoDB中添加数据库时,可能会遇到数据库问题.当我单击我的按钮时,它将运行以下代码:

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:

OPTIONS http://localhost:4000/users/ 401(未经授权)

无法加载 http://localhost:4000/users/:对预检请求的响应没有•通过访问控制检查:所请求的资源上不存在"Access-Control-Allow-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.

未捕获(承诺)TypeError:无法获取

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.

我使用Google Chrome浏览器作为默认浏览器.

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.

这篇关于在ReactJS中使用基本身份验证返回401(未经授权)进行抓取.飞行前请求未通过访问控制检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆