React和NodeJS跨域请求被阻止

时间:2020-09-02 21:26:31

标签: node.js reactjs cross-domain

我刚刚开始使用React和NodeJS。我创建了一个服务器端NodeJS应用程序,并试图使用Axios从我的React应用程序发送HTTP请求。

服务器正在运行端口8080 app.listen(process.env.PORT || 8080);

我的服务器控制器:

const User = require('../models/Users');
const UserModel = new User();

exports.login = async (req, res, next) => {
    const email = req.params.email;
    const password = req.params.password;
    const login = await UserModel.getUserLogin(email, password);
    res.status(202).send(JSON.stringify(login));
};

我的React应用程序是默认的http://localhost:3000

这是我给服务器打电话的地方

axios.get(Constants.SERVERURL + 'user/' + this.state.email + '/' + this.state.password,
    { crossDomain: true }
  ).then(res => {
    console.log(res);
  }).catch(err => {
    console.log(err);
  });

Constants.SERVERURL为export const SERVERURL = "http://localhost:8080/";

它返回错误:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/user/email@test.com/123. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing)

如何避免跨域问题?

谢谢

1 个答案:

答案 0 :(得分:0)

您应该将proxy添加到package.json,因为我记得这是解决CORS问题的最常见解决方案。

{
   proxy: "localhost:8080"
}

另一件事是关于安装cors软件包并将其作为中间件添加到您的Express服务器中,您可以按照以下方式进行操作。

const cors = reqiure("cors")

app.use(cors())