gpt4 book ai didi

javascript - Ajax POST 请求发送未定义到 Express

转载 作者:行者123 更新时间:2023-11-30 11:49:48 26 4
gpt4 key购买 nike

我正在尝试发送一些数据进行解析。客户端的脚本如下:

function addURL(link) {
console.log("Adding url...");
$.ajax({
type: "POST",
url: location.protocol + "//" + location.host + "/shorturl/create",
crossDomain: true,
contentType: "application/json",
data: JSON.stringify({url:link}),
success: function(data){
$("#shortenedURL").html(data.shortenedURL);
},
error: function(err){
console.log("Ran into an error... " + err);
}
});
}

在我的 express 应用程序中,在其中一个路由器上,我有:

router.post("/create", function(req, res){

console.log(req.body);
console.log(req.body.url);
var url = req.body.url; }

我得到“未定义”,然后是“无法获取未定义的属性‘url’”。

我不知道我哪里出错了......

最佳答案

您需要使用 bodyParser :

应用程序.js:

var bodyParser = require('body-parser')
, app = express();

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

关于javascript - Ajax POST 请求发送未定义到 Express,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39809783/

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