【问题标题】:How can I avoid 400 (Bad Request) from ajax PUT如何避免 ajax PUT 的 400 (Bad Request)
【发布时间】:2018-12-21 12:40:41
【问题描述】:

所以我得到了这个 JavaScript,它应该使用 ajax 向我的服务器发送一些带有 PUT 的数据。

var payload = 'id=' + id + '&brand=' + brand + '&model=' + model + '&country=' + country + '&number=' + number + '&alkohol=' + alkohol + '&volume=' + volume + '&price=' + price + '&comment=' + comment;

var fixedPayload = payload.split(' ').join('+'); // replace blanks with +

$.ajax({
        type: 'PUT',
        url: 'http://localhost:3000/drinks/' + fixedPayload,
        // data: fixedPayload, this does not work either
        success: function (data) {
            alert('Update was successfull!');
        }
    });

这是在服务器上

app.put('drinks/:id', (req, res) => {

    let id = req.params.id;
    var data = {
        brand: req.body.brand,
        model: req.body.model,
        country: req.body.country,
        number: req.body.number,
        alkohol: req.body.alkohol,
        volume: req.body.volume,
        price: req.body.price,
        comment: req.body.comment
    };
    Drink.findByIdAndUpdate(id, data, function(err, drink) {
        if (err) throw err;

        res.send('Drink updated - '+drink.model);
        });
});

这就是我得到的

jquery-3.3.1.min.js:2 PUT http://localhost:3000/drinks/?5c1b873a6a0a5d3ae0342f01&brand=L%C3%A4sk&model=Cola&country=Sverige&number=999&alkohol=0%&volume=33+cl&price=20&comment=Cola+asd 404(未找到)

Console.log(fixedPayload)

?5c1b873a6a0a5d3ae0342f01&brand=Läsk&model=Cola&country=Sverige&number=999&alkohol=0%&volume=33+cl&price=20&comment=Cola+asd

似乎是什么问题? 我也尝试发送一个对象而不是一个字符串,但结果相同

解决了

AJAX

package = {
    brand: brand,
    model: model,
    country: country,
    number: number,
    alkohol: alkohol,
    volume: volume,
    price: price,
    comment: comment        
};




$.ajax({
    type: 'PUT',
    url: `http://localhost:3000/drinks/${id}`, // changed it here
    data: package,
    success: function (data) {
        alert('Update was successfull!');
        window.location = "http://localhost:3000/";
    }
});

【问题讨论】:

  • 你的 url contanis / before ?.
  • 固定示例是(手动)进行表单编码。也许动态版本正在发送 JSON,但服务器应该是表单编码?
  • 另外,您引用的输出显示 404 状态(未找到),但标题显示 400(错误请求):这是什么? (它们确实意味着不同的东西。)
  • 也许将headers: {'content-type': 'application/json'} 添加到jquery.ajax?
  • 是的,我开始摆弄代码,var payload = '?' + id + '&brand'... 给出 404

标签: javascript node.js ajax express bad-request


【解决方案1】:

您的 URL 格式错误,我相信作为 URL 参数一部分的 id 应该是路径的一部分。在您的示例中:http://localhost:3000/drinks/5c1b873a6a0a5d3ae0342f01?brand=...

【讨论】:

    【解决方案2】:

    您的代码存在以下问题:

    • 您的端点drinks/:id 需要一个路径变量id,因为您在客户端上附加到drinks/ 一个查询字符串:'http://localhost:3000/drinks/' + fixedPayload
    • 当服务器期望参数在正文中时,您将参数作为查询字符串传递。 brand: req.body.brand

    这应该是这样的:

    var payload = '?brand=' + brand + '&model=' + model + '&country=' + country + '&number=' + number + '&alkohol=' + alkohol + '&volume=' + volume + '&price=' + price + '&comment=' + comment;
    
    var fixedPayload = payload.split(' ').join('+'); // replace blanks with +
    
    $.ajax({
            type: 'PUT',
            url: 'http://localhost:3000/drinks/' + id,
            data: fixedPayload,
            // data: fixedPayload, this does not work either
            success: function (data) {
                alert('Update was successfull!');
            }
        });
    

    【讨论】:

    • 哦,是的,我刚刚复制了一些其他代码,完全错过了它是正文而不是参数。但是,我不关注第一个问题。它应该是'localhost:3000/drinks' + id;数据:固定有效载荷; // 里面没有id? #菜鸟
    • 好吧,我现在有确切的代码,但我收到了 400 错误请求
    • 您是否在服务器端正确安装和设置了正文解析器? jquery 是否将数据作为 url 编码发送?
    • body-parser 应该可以正常工作。我有这些台词,我真的不知道它们在做什么。 app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: false }));如何检查 jquery 是否发送 url 编码的数据?
    【解决方案3】:

    创建 HTTP 请求很棘手(例如,% 字符需要编码,而您的代码没有这样做:这很可能是 400 错误的原因)。 jQuery 擅长为你做这件事。您可能最好让它通过传递对象而不是字符串来创建请求字符串。

    var payload = {
        id: id,
        brand: brand,
        model: model,
        country: country,
        number: number,
        alkohol: alkohol,
        volume: volume,
        price: price,
        comment: comment
    };
    
    $.ajax({
        type: 'PUT',
        url: 'http://localhost:3000/drinks/',
        data: payload,
        success: function (data) {
            alert('Update was successfull!');
        }
    });
    

    此外,您的服务器端代码需要drinks/:id 格式的请求,因此您可能实际上想要类似的东西

        url: 'http://localhost:3000/drinks/' + id,
    

    在您的 AJAX 设置对象中。

    【讨论】:

    • 这给了我一个 404。你会把“?”放在哪里?在这个例子中?它必须知道类型吗?这有关系吗? (应用程序/json)
    • @axlu 您不需要将? 放入:jQuery 将为您处理类似的事情。您没有提交 JSON,因此不需要contentType。我最好的猜测是,您需要按照我的回答更改 url 设置。
    • 好的,我试过你的代码,我仍然得到错误,jquery-3.3.1.min.js:2 PUT localhost:3000/drinks/5c1b873... 404 (Not Found) send @ jquery-3.3.1 .min.js:2 ajax@jquery-3.3.1.min.js:2 update@find.js:68 onclick@(index):1
    • @axlu 好了,400 错误修复了,那么!这是一个好的开始。现在你只需要弄清楚为什么请求没有被正确路由。最明显的原因是没有重新启动服务器,但我不是运行 Express 应用的专家。
    猜你喜欢
    • 1970-01-01
    • 2019-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-21
    • 2020-02-29
    • 1970-01-01
    相关资源
    最近更新 更多