代码之家  ›  专栏  ›  技术社区  ›  user944513

如何在使用Ajax请求时删除CORS错误?

  •  -4
  • user944513  · 技术社区  · 8 年前

    我正在尝试使用 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 对…的反应 飞行前请求未通过访问控制检查:的值 响应中的“访问控制允许来源”头不能是 当请求的凭据模式为“include”时使用通配符“*”。起源 ’ 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>
    

    服务器代码 服务器,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;
    

    控制器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)
            }
    
        },
    
    }
    

    护照号码

    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插件,但仍然出现同样的错误。

    2 回复  |  直到 8 年前
        1
  •  0
  •   Suresh Prajapati    8 年前

    最简单的方法是使用node.js包 cors . 最简单的用法是:

    var cors = require('cors')
    
    var app = express();
    
    app.use(cors());
    

    使用时 withCredentials: true 在Ajax中,CORS需要如下配置。

    app.use(cors({origin: 'http://localhost:3000', credentials: true}));
    
        2
  •  0
  •   Suresh Prajapati    8 年前

    你马上就要解决了。您需要将实际允许的主机发送到 Access-Control-Allow-Origin 头值与否 *

    如果你想考虑所有的起源,那么你可以包括 req.headers.origin 对于 访问控制允许来源 CORS中间件中的头值:

    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();
    });
    
    推荐文章