【发布时间】:2017-06-08 19:23:45
【问题描述】:
我正在尝试从运行在 4200 端口上的 angularJS 应用程序向运行在不同端口 3000 上的 nodeJS 应用程序发送发布请求,如下所示。
AngularJS 2.0 代码:
addNewItem(body:string) {
const headers = new Headers();
headers.append('Content-Type','application/json');
return this.http.post('http://10.244.1.59:3000/newBinDevice',body,{
headers: headers
})
.map((response : Response) => response.json());
}
NodeJS 代码
var express = require('express');
module.exports = function(app){
var db = require('./dbclient');
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
db.dbconnection(null,null,null,null,'smartbin',null);
app.post('/newItem', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
//res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Headers", "Content-Type");
res.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
console.log('body request is ' + req.body + " after stringifying it " + JSON.stringify(req.body) + " array to string " + req.body.toString());
}
我收到了 CORS 问题,说 " Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 404." 我在某处读到除了
application/x-www-form-urlencoded
multipart/form-data
text/plain
当我尝试从 AngularJS 应用程序发送数据作为字符串而不是 JSON 对象时,我在 nodejs 应用程序上得到空数据。
【问题讨论】:
标签: angularjs node.js cors http-post