【问题标题】:Ajax POST request sending undefined to ExpressAjax POST 请求发送未定义到 Express
【发布时间】:2016-10-01 17:56:06
【问题描述】:

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

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; }

我得到'undefined',然后'Cannot get property 'url' of undefined'。

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

【问题讨论】:

  • 您确定您发送的 url: 链接在 ajax 上有值吗?
  • 您使用的是什么 expressjs 版本并发布您的 app.js 代码

标签: javascript ajax node.js express


【解决方案1】:

你需要使用bodyParser:

app.js:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-08
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 2021-01-05
    • 2019-07-21
    • 2022-10-12
    • 2016-08-09
    相关资源
    最近更新 更多