我一直在阅读我发现的关于CORS的所有文章,但我仍然无法解决这个问题 - 没有'Access-Control-Allow-Origin'。
我需要使用jquery ajax向我的node / expressjs服务器发出发布请求,但我无法使其正常工作。
这是我的ajax代码:
$.ajax({
url: 'http://mydevserver:3000/api/nnnn',
type: "POST",
data: data,
contentType: "application/json",
async: true,
success: function(data) {
console.log("success!");
}
});
这是我设置响应头的expressJS部分:
var corsOrigin ;
if (process.env.NODE_ENV == 'production') {
console.log('Adding CORS to the headers...');
corsOrigin = 'myprodserver';
}
else {
corsOrigin = 'http://mydevserver:4200';
}
app.use(function(req, res, next) {
res.set("Access-Control-Allow-Origin", corsOrigin);
res.set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.set('Access-Control-Allow-Methods', 'POST, GET, PUT, PATCH, DELETE, OPTIONS');
next();
});
我在这里缺少什么?我的选择用完了......
非常感谢您的帮助!
我最诚挚的问候。
更新1 - 完整的服务器和路由代码
server.js
var http = require('http');
var app = require('./app');
/**
* Get port from environment and store in Express.
*/
console.log('Server port set to ' + process.env.NODE_PORT);
var port = normalizePort(process.env.NODE_PORT || '3000');
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
console.log('Listening on ' + bind);
}
app.js
var express = require('express');
var path = require('path');
var AWS = require("aws-sdk");
var app = express();
var bodyParser = require('body-parser');
var fs = require('fs');
var cors = require("cors");
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: 150000000, extended: true, parameterLimit:50000}));
var corsOrigin ;
if (process.env.NODE_ENV == 'production') {
console.log('Adding CORS to the headers...');
corsOrigin = 'prodserver';
}
else {
corsOrigin = 'http://localhost:4200';
}
app.use(function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', corsOrigin);
res.setHeader("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT,DELETE");
res.set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
res.set('Access-Control-Allow-Credentials', 'true');
next();
});
var globSync = require('glob').sync;
var routes = globSync('./routes/*.js', { cwd: __dirname}).map(require);
AWS.config.update({
region: "xxxx",
accessKeyId: "xxxx",
secretAccessKey: "xxxxxxx"
});
var ddb = new AWS.DynamoDB.DocumentClient();
routes.forEach( function(route) {
route(app, ddb);
});
app.use('/', express.static(path.join(__dirname, 'dist')));
app.use('/api/resources', express.static(path.join(__dirname, 'resources')));
module.exports = app;
答案 0 :(得分:0)
正如sideshowbarker所指出的那样,我在我的ajax调用中传递了contentType:“application / json”。那就是问题所在。以下是工作代码:
$.ajax({
url: 'http://mydevserver:3000/api/nnnn',
type: "POST",
data: data,
async: true,
success: function(data) {
console.log("success!");
}
});
谢谢大家的帮助!
答案 1 :(得分:-1)
在快递节点中尝试这样:
var origin = "http://localhost:4200";
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', origin || "*");
res.header('Access-Control-Allow-Methods', 'GET,POST,PUT,HEAD,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'content-Type,x-requested-with');
next();
});