ExpressJS:对预检请求的响应未通过访问控制检查

时间:2018-02-20 00:16:23

标签: angular express

我正在http://localhost:4200上运行Angular 4(angular.io/angular cli)应用以及http://localhost:3000上的ExpressJS应用

ExpressJS app github link

Angular app github link

我尝试了什么

我在这个问题上花了好几个小时,我找到了一个解决方案,即使用chrome扩展来禁用CORS。 我试图在ExpressJS应用程序中自己添加CORS的中间件头文件,因为我读过这只是服务器端问题而不是客户端问题,因此它不是角度问题。 我试图添加cors npm模块。那也行不通。 我故意在我的路线和路线之前添加了cors线路。 app.js中的静态文件夹定义。 我不知道问题是什么..

错误

  

无法加载http://localhost:3000/users/post:对预检的响应   请求未通过访问控制检查:否   请求中存在“Access-Control-Allow-Origin”标头   资源。因此不允许来源“http://localhost:4200”   访问。

ExpressJS应用程序中的console.log

OPTIONS /users/post 200 1.206 ms - 13

200怎么样?为什么它认为没关系?

app.js

    var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var app = express();

// Add headers
/*
app.use(function (req, res, next) {

    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);

    // Pass to next layer of middleware
    next();
});
*/

/*var corsOptions = {
    origin: ['http://localhost:4200'],
    optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
};
const corsOptions = {
    origin: '*',
    method: ['GET', 'POST'],
    //allowedHeaders: ['Content-Type', 'Authorization', 'Origin', 'Accept', 'X-Requested-With'],
    optionsSuccessStatus: 200 //Some legacy browsers (IE11, various SmartTVs) choke on 204
};
app.use(cors(corsOptions));
app.options('*', cors());
*/

const corsOptions = {
    origin: 'http://localhost:4200',
    method: ['GET', 'POST'],
    //allowedHeaders: ['Content-Type', 'Authorization', 'Origin', 'Accept', 'X-Requested-With'],
    optionsSuccessStatus: 200 //Some legacy browsers (IE11, various SmartTVs) choke on 204,
    credentials: true
};
app.use(cors(corsOptions));

var index = require('./routes/index');
var users = require('./routes/users');

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handler
app.use(function (err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

    // render the error page
    res.status(err.status || 500);
    res.render('error');
});

module.exports = app;

users.js

    var express = require('express');
var router = express.Router();

var conn = require('../connect')();
//var cors = require('cors');
var table = "users";

router.get('/', (req, res, next) => {
    var query = `SELECT * FROM ${table}`;
    console.log(query);

    conn.query(query, (err, result, fields) => {
        if (err) throw err;
        res.send(result);
    });
});

router.post('/post', (req, res) => {

    //console.log("Body: ", req.body);
    /**
     * Test Case:
     * {"user":{"name": "jack","email": "jack@gmail.com","password": "jackPass"}}
     * */

    var name = req.body.name;
    var email = req.body.email;
    var password = req.body.password;

    var query = `INSERT INTO ${table} VALUES (null, "${name}", "${email}", "${password}")`;
    console.log(query);

    conn.query(query, (err, result, fields) => {
        if (err) throw err;
        res.send(result);
    });
});

router.get('/:search/', (req, res, next) => {

    var search = req.params.search;
    var query = "";

    if (isNaN(search)) {
        query = `SELECT * FROM ${table} WHERE name LIKE '%${search}%'`;
    } else {
        query = `SELECT * FROM ${table} WHERE id='${search}'`;
    }
    console.log(query);

    conn.query(query, (err, result, fields) => {
        if (err) throw err;
        res.send(result);
    });
});

module.exports = router;
var express = require('express');
var router = express.Router();

var conn = require('../connect')();
//var cors = require('cors');
var table = "users";

router.get('/', (req, res, next) => {
    var query = `SELECT * FROM ${table}`;
    console.log(query);

    conn.query(query, (err, result, fields) => {
        if (err) throw err;
        res.send(result);
    });
});

router.post('/post', (req, res) => {

    //console.log("Body: ", req.body);
    /**
     * Test Case:
     * {"user":{"name": "jack","email": "jack@gmail.com","password": "jackPass"}}
     * */

    var name = req.body.name;
    var email = req.body.email;
    var password = req.body.password;

    var query = `INSERT INTO ${table} VALUES (null, "${name}", "${email}", "${password}")`;
    console.log(query);

    conn.query(query, (err, result, fields) => {
        if (err) throw err;
        res.send(result);
    });
});

router.get('/:search/', (req, res, next) => {

    var search = req.params.search;
    var query = "";

    if (isNaN(search)) {
        query = `SELECT * FROM ${table} WHERE name LIKE '%${search}%'`;
    } else {
        query = `SELECT * FROM ${table} WHERE id='${search}'`;
    }
    console.log(query);

    conn.query(query, (err, result, fields) => {
        if (err) throw err;
        res.send(result);
    });
});

module.exports = router;

1 个答案:

答案 0 :(得分:2)

在您的快递app.js

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");
  next();
//rest of your app.get/post/whatevers

这应该为你提供角色。