当响应客户端尝试获取数据时,如何解决CORS请求在express.js中未成功? [英] How to solve CORS request did not succeed in express.js when react client try fetch data?

查看:106
本文介绍了当响应客户端尝试获取数据时,如何解决CORS请求在express.js中未成功?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 app.js 文件中做了很多更改以解决此问题 CORS请求未成功,但是我总是面临着同样的问题。如何解决这个问题。我添加了我的app.js代码,请检查任何人。谢谢

I done so many changes in app.js file to solve this issue CORS request did not succeed but i always facing the same issue.How to solve this issue. I added my app.js code please check anyone. thanks

app.js代码

var express = require('express');

var bodyParser = require("body-parser");
var app = express();
var cors = require('cors');

const userlogin   = require('./routes/User_route');
const deviceRoutes = require("./routes/Device_route");

app.use('*', cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.set('port', process.env.PORT || 4007);
app.set('host', "*.*.*.*"); 

app.use("/users",userlogin);
app.use("/users", deviceRoutes);
module.exports = app;

错误


TypeError:尝试获取资源时出现NetworkError。
bundle.js:132447:16

TypeError: "NetworkError when attempting to fetch resource." bundle.js:132447:16

跨域请求被阻止:同源策略禁止读取
远程资源,位于 http:// localhost:4007 / users / login 。 (原因:
CORS请求未成功。)

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:4007/users/login. (Reason: CORS request did not succeed).


推荐答案

您可以尝试

//CORS middleware
var corsMiddleware = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', 'localhost'); //replace localhost with actual host
    res.header('Access-Control-Allow-Methods', 'OPTIONS, GET, PUT, PATCH, POST, DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type, X-Requested-With, Authorization');

    next();
}

app.use(corsMiddleware);

这篇关于当响应客户端尝试获取数据时,如何解决CORS请求在express.js中未成功?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆