【问题标题】:Unhandled Rejection (TypeError): Failed to fetch in React未处理的拒绝(TypeError):无法在 React 中获取
【发布时间】:2021-12-20 05:31:45
【问题描述】:

我是反应新手。我在反应中使用 jwt 身份验证。登录 api 在邮递员中运行良好。我使用 tha api url 并尝试从 react 发布数据,但它说 -

访问 'http://localhost:3000/' 获取(重定向自 'http://127.0.0.1:8000/api/login') 来自来源 'http://localhost:3000' 已被 CORS 策略阻止:没有“访问控制允许来源” 请求的资源上存在标头。如果一个不透明的响应 满足您的需求,将请求的模式设置为“no-cors”以获取 禁用 CORS 的资源。

这是源代码:

import {memo} from 'react'
import React, { Component } from 'react'

export default class Test extends Component {
    constructor(){
        super();
        this.state= {
            email:null,
            password:null,
           
        }
    }
    login(){
        console.log(this.state);
        fetch('http://127.0.0.1:8000/api/login',{
            method:'POST',
            body: JSON.stringify(this.state)
        }).then((res)=>res.json().then((result)=>{console.log(result)}))
    }
    render() {
        return (
            <div>
                <input type='email' placeholder='email' onChange={(e)=>{this.setState({email:e.target.value})}}/><br/>
                <input type='password' placeholder='password' onChange={(e)=>{this.setState({password:e.target.value})}}/>
                <button type='button' onClick={()=>{this.login()}}>Login</button>
            </div>
        )
    }
}

如何解决?

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    这称为 CORS 错误。基本上,与您的 Web 应用程序相比,您的应用程序正在请求不同来源的资源。为了解决这个问题,您必须使用 Access-Control-Allow-Origin 在您的服务器中将此域列入白名单,或者您需要在您的服务器中启用 CORS。

    【讨论】:

      猜你喜欢
      • 2017-11-20
      • 2020-07-15
      • 2021-05-17
      • 1970-01-01
      • 2019-08-06
      • 1970-01-01
      • 2023-03-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多