【问题标题】:Cannot fix Error while fetching - React.js获取时无法修复错误 - React.js
【发布时间】:2021-09-11 15:09:28
【问题描述】:

我已经编写了这段代码,我正在尝试获取数据,一切正常,但没有显示数据,当我检查时出现此错误:

CORS 策略阻止了从源“http://localhost:8080/users”获取的访问权限:不存在“Access-Control-Allow-Origin”标头请求的资源。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。

这是我的代码

import React, {useEffect, useState} from 'react'
import ReactDOM from 'react-dom'

export class UserComponent extends React.Component{

    constructor(props){
        super(props);
        this.state={users:[], addModalShow:false, editModalShow:false}
    }

    componentDidMount() {
        this.refreshList();
    }
    
    refreshList(){
        fetch('http://localhost:8080/users')
        .then(response => response.json())
        .then(data => {
            this.setState({users:data})
        });
    }

    render(){
        const {users, userId, FirstName, Username, LastName, Phone, Password, Address} = this.state;

        return(


            <div>
                <table>
                    <thead>
                        <tr>
                            <th>Id</th>
                            <th>First Name</th>
                            <th>Last Name</th>
                            <th>Username</th>
                            <th>Password</th>
                            <th>Address</th>
                            <th>Phone</th>
                        </tr>
                    </thead>
                    <tbody>
                        {users.length>0 && users.map((user)=>(
                            <tr key={user.Id}>
                                <td>{user.Id}</td>
                                <td>{user.FirstName}</td>
                                <td>{user.LastName}</td>
                                <td>{user.Username}</td>
                                <td>{user.Password}</td>
                                <td>{user.Adress}</td>
                                <td>{user.Phone}</td>
                            </tr>
                        ))}
                    </tbody>
                </table>
            </div>
        );
    }
}

const element=<UserComponent></UserComponent>
ReactDOM.render(element, document.getElementById('root'));

如果有人可以帮助我,我会很高兴。

【问题讨论】:

    标签: javascript sql reactjs cors


    【解决方案1】:

    只需在你的前端 package.json 中添加 "proxy": "http://localhost:3000",

    为了理解上面的sn-p做的,可以参考this

    【讨论】:

      猜你喜欢
      • 2022-11-29
      • 1970-01-01
      • 2021-04-02
      • 1970-01-01
      • 1970-01-01
      • 2015-07-24
      • 2016-08-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多