【发布时间】:2018-06-13 17:15:33
【问题描述】:
我正在使用 node.js 为服务器端和 angular 前端部分做一个应用程序。我在使用简单的 post 方法时遇到问题,问题是当我将 json 发送到服务器时,它就像 json 密钥一样使用它。我正在使用body-parser,也许问题出在那个?这是我的代码:
角度:
var request = $http({
method: "POST",
url: 'http://localhost:3000/register',
data: {
"username": "filip"
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
node.js
var express = require("express");
var bodyParser = require("body-parser");
var morgan = require("morgan");
var app = express();
var config = require("./config");
var mongodb = require("mongodb")
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.use(morgan("dev"));
app.post("/register", function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8080');
// 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);
console.log(req.body);
});
这就是我在服务器上收到的请求:
{ '{"username":"filip"}': '' }
我刚刚开始学习 node.js,我被这个简单的东西困住了, 有人帮忙吗?
【问题讨论】:
标签: javascript angularjs node.js