【发布时间】:2019-01-30 23:39:51
【问题描述】:
我有一个 Nodejs express 服务器和一个将数据发送到服务器的 angularJs 客户端。
问题是当我尝试使用 angularJS 向服务器发送 JSON 时,收到的 JSON 变成这样:
{"{\"question\":\"What will be result of code int a ":" 5/2\",\"answers\":[{\"a\":\"2.50\",\"b\":\"1\",\"c\":\"2\",\"d\":\"no right answer\"}],\"answer\":\"c\",\"score\":\"100\"}"}
这是我在 angularJS 中的 post 方法:
createQuestion: function(question){
delete question["_id"];
console.log(JSON.stringify(question))
return $http.post('http://localhost:3000/questions/', question, {
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
})
.then(
function(response){
return response.data;
},
function(errResponse){
console.error('Error while creating question');
return $q.reject(errResponse);
}
);
}
console.log(JSON.stringify(question)) 的输出是:
{"question":"What will be result of code int a = 5/2","answers":[{"a":"2.50","b":"1","c":"2","d":"no right answer"}],"answer":"c","score":"100"}
这是nodejs中负责POST方法的部分代码:
exports.create_a_question = function(req, res) {
console.log(JSON.stringify(req.body))
var new_question = new Question(req.body);
new_question.save(function(err, question) {
if (err)
res.send(err);
res.json(question);
});
};
经过搜索,我发现这个问题是由于请求标头中的application/x-www-form-urlencoded 而发生的,但是我将此配置添加到我的nodejs服务器并且问题仍然存在:
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
这是 nodejs 服务器上的 CORS 标头:
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
res.setHeader('Access-Control-Max-Ag', '3600');
我该如何解决这个问题?
【问题讨论】:
-
如果要发送json,为什么要使用
Content-Type: x-www-form-urlencoded?此外,angularjs 不会强化您的数据:stackoverflow.com/questions/24545072/… -
尝试从
$http.post请求中删除headers。 -
@Andrew 因为使用 application/json 在角度上返回 404 forum.ionicframework.com/t/…
-
@31piy 我这样做了,但我得到了 404 错误forum.ionicframework.com/t/…
-
@我已经更新了我的问题,包括标题
标签: angularjs json node.js express