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

2023-10-02前端开发问题
46

本文介绍了使用 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.

这篇关于使用 Basic Auth 获取 ReactJS 返回 401(未授权).预检请求未通过访问控制检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

js删除数组中指定元素的5种方法
在JavaScript中,我们有多种方法可以删除数组中的指定元素。以下给出了5种常见的方法并提供了相应的代码示例: 1.使用splice()方法: let array = [0, 1, 2, 3, 4, 5];let index = array.indexOf(2);if (index -1) { array.splice(index, 1);}// array = [0,...
2024-11-22 前端开发问题
182

JavaScript小数运算出现多位的解决办法
在开发JS过程中,会经常遇到两个小数相运算的情况,但是运算结果却与预期不同,调试一下发现计算结果竟然有那么长一串尾巴。如下图所示: 产生原因: JavaScript对小数运算会先转成二进制,运算完毕再转回十进制,过程中会有丢失,不过不是所有的小数间运算会...
2024-10-18 前端开发问题
301

JavaScript(js)文件字符串中丢失"\"斜线的解决方法
问题描述: 在javascript中引用js代码,然后导致反斜杠丢失,发现字符串中的所有\信息丢失。比如在js中引用input type=text onkeyup=value=value.replace(/[^\d]/g,) ,结果导致正则表达式中的\丢失。 问题原因: 该字符串含有\,javascript对字符串进行了转...
2024-10-17 前端开发问题
437

layui中table列表 增加属性 edit="date",不生效怎么办?
如果你想在 layui 的 table 列表中增加 edit=date 属性但不生效,可能是以下问题导致的: 1. 缺少日期组件的初始化 如果想在表格中使用日期组件,需要在页面中引入 layui 的日期组件,并初始化: script type="text/javascript" src="/layui/layui.js"/scrip...
2024-06-11 前端开发问题
455

Rails/Javascript:如何将 rails 变量注入(非常)简单的 javascript
Rails/Javascript: How to inject rails variables into (very) simple javascript(Rails/Javascript:如何将 rails 变量注入(非常)简单的 javascript)...
2024-04-20 前端开发问题
5

“数组中的每个孩子都应该有一个唯一的 key prop"仅在第一次呈现页面时
quot;Each child in an array should have a unique key propquot; only on first time render of page(“数组中的每个孩子都应该有一个唯一的 key prop仅在第一次呈现页面时)...
2024-04-20 前端开发问题
5