简体   繁体   English

节点快递网站与 REST 身份验证 API - CORS 问题

[英]node express website with REST authentication API - CORS problem

I am new to nodejs + Express but I'm trying to build a very quick proof of concept website which allows user to authenticate via a REST API.我是 nodejs + Express 的新手,但我正在尝试构建一个非常快速的概念验证网站,该网站允许用户通过 REST API 进行身份验证。

I have come against a CORS problem and despite installing the cors module and using it as suggested in the documentation , I am still getting the following error:我遇到了 CORS 问题,尽管安装了 cors 模块并按照文档中的建议使用它,但我仍然收到以下错误:

Access to XMLHttpRequest at xxx has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header has a value ' https://www.example.com ' that is not equal to the supplied origin. Access to XMLHttpRequest at xxx has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header has a value ' https://www.example.com ' that不等于提供的原点。

Here is my (simplified) code:这是我的(简化的)代码:

app.js应用程序.js

const express = require('express');
const expressLayouts = require('express-ejs-layouts');
const cors = require('cors');

compression = require('compression'),
shouldCompress = (req, res) => {
    if (req.headers['x-no-compression']) {
      // don't compress responses if this request header is present
      return false;
    }
    // fallback to standard compression
    return compression.filter(req, res);
  };

const app = express();


// EJS
app.use(expressLayouts);
app.set('view engine', 'ejs');

// Parsing related
app.use(express.urlencoded( { extended: false })); //Parse URL-encoded bodies
app.use(express.json()); //Used to parse JSON bodies

app.use(compression({
    filter:shouldCompress,
    threshold: 3
}));

app.use(express.static('public'));
app.disable('x-powered-by');


// Using the flash middleware provided by connect-flash to store messages in session
// and displaying in templates
const flash = require('connect-flash');
app.use(flash());

// Sessions
const session = require('express-session');

app.use(session({
  secret: 'fat cat 42',
  resave: false,
  saveUninitialized: true,
  cookie: { secure: true }
}));

// Initialize Passport and restore authentication state, if any, from the session.
const passport = require('passport');
require ('./config/passport')(passport);
app.use(passport.initialize());
app.use(passport.session())

// Routes
app.use('/', require('./routes/index'));
app.use('/member', require('./routes/users'));


const PORT = process.env.PORT || 5000;

app.listen(PORT, console.log(`Server started on port: ${PORT}`));

users.js用户.js

const express = require('express');
const router = express.Router();
const passport = require('passport');

require ('../config/passport')(passport);


router.post('/signin', passport.authenticate('facebook', {
    successRedirect : '/home',
    failureRedirect : '/'
  }));

module.exports = router;

Here is the script portion of the view that makes the AJAX POST这是使 AJAX POST 的视图的脚本部分

homepage.ejs主页.ejs

   $(document).ready(function(){
      $('#demo').click(function(e){
        $.ajax({
          method: "POST",
          url: "/member/signin",
          data: {
            "source": $(this).attr('id')
          },
          dataType: "json",
          timeout: 5000 // 5000ms
        }).done(function(data) {
          // is called if request is successful
          console.log('Success:' + data);
        }).fail(function(jqXHR, status) {
          // is called if request fails or timeout is reached
          alert('Request could not complete: ' + status);
        });
      });
    });

How do I fix this so that the AJAX calls work?如何解决此问题,以便 AJAX 调用正常工作?

essentially you need to permit cross-site origin requests.本质上,您需要允许跨站点源请求。 you do that by setting the access-control-headers normally with some proxy like nginx in front of your node server like the following (it is not recommended to have node directly exposed on port 80)您可以通过在节点服务器前面使用 nginx 之类的代理来正常设置access-control-headers ,如下所示(不建议将节点直接暴露在端口 80 上)

#nginx config
if ($request_method = 'OPTIONS') {
    add_header 'Access-Control-Allow-Origin' '*';
    add_header 'Access-Control-Allow-Credentials' 'true';
    add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, HEAD, DELETE, OPTIONS';
    add_header 'Access-Control-Allow-Headers' 'Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Requested-With';
    return 204;
}

if you have expressjs you could use this cors middleware如果你有 expressjs,你可以使用这个 cors 中间件

var express = require('express')
var cors = require('cors')
var app = express()

app.use(cors())

app.post('/signin/', function (req, res, next) {
    // ....
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM