gpt4 book ai didi

javascript - AngularJS http post 不适用于 Node 服务器

转载 作者:行者123 更新时间:2023-11-30 11:33:13 25 4
gpt4 key购买 nike

我的 Node 后端服务器中有这段代码:

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

这是 API,即我想调用:

router.post('/update/:_id', function(req, res, next) {
console.log("req.body:" + req.body);
}

这是我通过 Angular 1 发出的帖子请求:

var data = {something: "something"}
var url = 'http://localhost:8081/update/5982168b399ccf32ad75ce2e';

$http({
withCredentials: false,
method: 'POST',
url: url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: data
})
.then(function (response) {
if (response.data) {
console.log("Post Data Submitted Successfully!");
}
}, function (response) {
console.log("Error status: " + response.status)
});

我使用的是 Angular 1.6.1 版本。

我尝试了所有方法并浏览了无数帖子,但没有一个对我有帮助。我可以看到 body 穿过。但是我在 Node 端后端得到了未定义的req.body

如有任何帮助,我们将不胜感激。

谢谢。

最佳答案

这可能是

headers: {'Content-Type': 'application/x-www-form-urlencoded'}

您的数据是 JSON 格式,而不是 x-www-form-urlencoded

{something: "something"}

你可以试试这个

headers: {'Content-Type': 'application/json'}

默认情况下,您在 $http POST 中发送 JSON 数据,因此您可能不需要 header 拿出来试试

============================================= ================

此外,您的数据可能不是有效格式JS 不知道是什么东西,它不是变量,对吧?你必须把它变成一个字符串,即使它是 { "key": "value"} 对的键如果上面不起作用,你可以试试这个

{
"something": "something"
}

验证您的 JSON https://jsonlint.com/

关于javascript - AngularJS http post 不适用于 Node 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45490533/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com