使用ajax请求时如何删除cors错误?
Posted
技术标签:
【中文标题】使用ajax请求时如何删除cors错误?【英文标题】:how to remove cors error while using ajax request? 【发布时间】:2019-01-27 06:34:53 【问题描述】:我正在尝试使用带有跨域护照的express-session
进行会话。我借助以下链接
Sending credentials with cross-domain posts?
Passport js fails to maintain session in cross-domain
**I am getting below error**
未能加载http://localhost:5000/users/login:响应 预检请求未通过访问控制检查: 响应中的“Access-Control-Allow-Origin”标头不能是 当请求的凭据模式为“包含”时,通配符“*”。起源 'http://localhost:3000' 因此不允许访问。这 XMLHttpRequest 发起的请求的凭证模式是 由 withCredentials 属性控制。
这是我的全部代码 https://github.com/naveennsit/Cors
客户端 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link href="style/style.css" rel="stylesheet" type="text/css"/>
<script src="../node_modules/jquery/dist/jquery.js"></script>
<script src="jquery.js"></script>
</head>
<body>
<script>
$(function ()
$.ajax(
url: 'http://localhost:5000/users/login',
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(id: 5),
dataType: 'json',
xhrFields:
withCredentials: true,
,
crossDomain: true,
success: function ()
console.log('success');
,
error: function ()
console.log('error')
);
)
</script>
</body>
</html>
服务器代码 server.js
var app = require('./app');
const PORT = process.env.PORT || 5000;
app.listen(PORT, () =>
console.log(`app is running on $PORT`);
)
app.js
const express = require('express');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const path = require('path');
const morgan = require('morgan');
const cors = require('cors');
const session = require('express-session');
const passport = require('passport');
const app = express();
// Middleware
app.use(bodyParser.urlencoded(extended: false));
app.use(bodyParser.json());
app.use(morgan('dev'));
app.use(cookieParser());
app.use(cors());
app.use(cookieParser());
app.use(function(req, res, next)
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, authorization");
res.header("Access-Control-Allow-Methods", "GET,POST,DELETE,PUT,OPTIONS");
next();
);
app.use(session(
secret: 'secret',
resave: false,
domain: '.localhost:3000',
saveUninitialized: false,
cookie:
domain: '.localhost:3000',
maxAge: 24 * 6 * 60 * 10000
,
))
app.use(passport.initialize());
app.use(passport.session());
//Routes
app.use('/users', require('./routes/user.route'))
module.exports = app;
controller.js
const passport = require('passport');
const passportConfig = require('../passport')
module.exports =
login: async (req, res, next) =>
console.log(req.body);
try
req.login(req.body.id, function ()
res.json(message: "Registration successfully");
)
catch (e)
console.log(e)
,
passport.js
const passport = require('passport');
passport.serializeUser(function(id, done)
console.log('ddd');
// console.log(user);
done(null, id);
);
passport.deserializeUser(function(id, done)
console.log('deserializeUser');
done(null, id);
// db.User.findById(id, function (err, user)
// done(err, user);
// );
);
路线
const express = require('express');
const router = require('express-promise-router')();
const controller = require('../controllers/user.controller');
router.route('/login',)
.post(controller.login)
module.exports = router;
我想在跨域中添加会话。我已经应用了 cors 插件仍然遇到同样的错误
【问题讨论】:
How to allow CORS?的可能重复 @LaxmikantDange 我已经申请了这些东西 这不是重复的问题 【参考方案1】:最简单的方法是使用node.js 包cors。最简单的用法是:
var cors = require('cors')
var app = express();
app.use(cors());
在ajax中使用withCredentials: true
时,cors需要如下配置。
app.use(cors(origin: 'http://localhost:3000', credentials: true));
【讨论】:
请删除这个答案 你配置了origin吗? 没用,请在 github 上查看我的代码。如果您有 2 分钟的时间,请告诉我哪里做错了 您需要在访问控制中添加凭据,(请参阅更新的答案)并且您在使用 cors (` res.header("Access-Control-Allow-Origin", "");` 这是个问题!所以评论 ``` / app.use(function(req, res, next) res.header("Access-Control-Allow-Origin", "*" ); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, authentication"); res.header("Access-Control-Allow-Methods", " GET,POST,DELETE,PUT,OPTIONS"); next(); ); */ ``` 让我们continue this discussion in chat。【参考方案2】:您几乎可以解决它。您需要在 Access-Control-Allow-Origin
标头值中发送实际允许的主机,而不是 *
如果您想允许所有来源,那么您可以在 CORS 中间件中包含 req.headers.origin
的 Access-Control-Allow-Origin
标头值:
app.use(function(req, res, next)
res.header("Access-Control-Allow-Origin", req.headers.origin);
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, authorization");
res.header("Access-Control-Allow-Methods", "GET,POST,DELETE,PUT,OPTIONS");
next();
);
【讨论】:
以上是关于使用ajax请求时如何删除cors错误?的主要内容,如果未能解决你的问题,请参考以下文章
如何在 AppHarbor 上接受 CORS AJAX 请求?