<i id='g70r3'><tr id='g70r3'><dt id='g70r3'><q id='g70r3'><span id='g70r3'><b id='g70r3'><form id='g70r3'><ins id='g70r3'></ins><ul id='g70r3'></ul><sub id='g70r3'></sub></form><legend id='g70r3'></legend><bdo id='g70r3'><pre id='g70r3'><center id='g70r3'></center></pre></bdo></b><th id='g70r3'></th></span></q></dt></tr></i><div id='g70r3'><tfoot id='g70r3'></tfoot><dl id='g70r3'><fieldset id='g70r3'></fieldset></dl></div>
      • <bdo id='g70r3'></bdo><ul id='g70r3'></ul>
    1. <legend id='g70r3'><style id='g70r3'><dir id='g70r3'><q id='g70r3'></q></dir></style></legend>

        <small id='g70r3'></small><noframes id='g70r3'>

        <tfoot id='g70r3'></tfoot>

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

        Fetch in ReactJS with Basic Auth return 401 (Unauthorized). Preflight request doesn#39;t pass access control check(使用 Basic Auth 获取 ReactJS 返回 401(未授权).预检请求未通过访问控制检查)
          <bdo id='wGyIV'></bdo><ul id='wGyIV'></ul>
          1. <tfoot id='wGyIV'></tfoot>

            <small id='wGyIV'></small><noframes id='wGyIV'>

              • <i id='wGyIV'><tr id='wGyIV'><dt id='wGyIV'><q id='wGyIV'><span id='wGyIV'><b id='wGyIV'><form id='wGyIV'><ins id='wGyIV'></ins><ul id='wGyIV'></ul><sub id='wGyIV'></sub></form><legend id='wGyIV'></legend><bdo id='wGyIV'><pre id='wGyIV'><center id='wGyIV'></center></pre></bdo></b><th id='wGyIV'></th></span></q></dt></tr></i><div id='wGyIV'><tfoot id='wGyIV'></tfoot><dl id='wGyIV'><fieldset id='wGyIV'></fieldset></dl></div>
                  <tbody id='wGyIV'></tbody>
              • <legend id='wGyIV'><style id='wGyIV'><dir id='wGyIV'><q id='wGyIV'></q></dir></style></legend>

                  本文介绍了使用 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(未授权).预检请求未通过访问控制检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

                  本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

                  相关文档推荐

                  在开发JS过程中,会经常遇到两个小数相运算的情况,但是运算结果却与预期不同,调试一下发现计算结果竟然有那么长一串尾巴。如下图所示: 产生原因: JavaScript对小数运算会先转成二进制,运算完毕再转回十进制,过程中会有丢失,不过不是所有的小数间运算会
                  问题描述: 在javascript中引用js代码,然后导致反斜杠丢失,发现字符串中的所有\信息丢失。比如在js中引用input type=text onkeyup=value=value.replace(/[^\d]/g,) ,结果导致正则表达式中的\丢失。 问题原因: 该字符串含有\,javascript对字符串进行了转
                  Rails/Javascript: How to inject rails variables into (very) simple javascript(Rails/Javascript:如何将 rails 变量注入(非常)简单的 javascript)
                  quot;Each child in an array should have a unique key propquot; only on first time render of page(“数组中的每个孩子都应该有一个唯一的 key prop仅在第一次呈现页面时)
                  CoffeeScript always returns in anonymous function(CoffeeScript 总是以匿名函数返回)
                  Ordinals in words javascript(javascript中的序数)

                    • <bdo id='8CMGH'></bdo><ul id='8CMGH'></ul>
                        <tbody id='8CMGH'></tbody>
                    • <tfoot id='8CMGH'></tfoot>

                          <i id='8CMGH'><tr id='8CMGH'><dt id='8CMGH'><q id='8CMGH'><span id='8CMGH'><b id='8CMGH'><form id='8CMGH'><ins id='8CMGH'></ins><ul id='8CMGH'></ul><sub id='8CMGH'></sub></form><legend id='8CMGH'></legend><bdo id='8CMGH'><pre id='8CMGH'><center id='8CMGH'></center></pre></bdo></b><th id='8CMGH'></th></span></q></dt></tr></i><div id='8CMGH'><tfoot id='8CMGH'></tfoot><dl id='8CMGH'><fieldset id='8CMGH'></fieldset></dl></div>
                          1. <legend id='8CMGH'><style id='8CMGH'><dir id='8CMGH'><q id='8CMGH'></q></dir></style></legend>

                            <small id='8CMGH'></small><noframes id='8CMGH'>