如何避免Ajax PUT中的400(错误请求)

时间:2018-12-21 12:40:42

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

所以我得到了这个JavaScript,它应该使用AUT的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/";
    }
});

3 个答案:

答案 0 :(得分:0)

创建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设置对象中。

答案 1 :(得分:0)

这是您的代码存在的问题:

  • 您的端点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!');
        }
    });

答案 2 :(得分:0)

您的URL格式错误,我确实相信object Diameter extends Serializable { type SPMap = Map[VertexId, Int] def makeMap(x: (VertexId, Int)*) = Map(x: _*) def incrementMap(spmap: SPMap): SPMap = spmap.map { case (v, d) => v -> (d + 1) } def addMaps(spmap1: SPMap, spmap2: SPMap): SPMap = { (spmap1.keySet ++ spmap2.keySet).map { k => k -> math.min(spmap1.getOrElse(k, Int.MaxValue), spmap2.getOrElse(k, Int.MaxValue)) }(collection.breakOut) // more efficient alternative to [[collection.Traversable.toMap]] } // Removed landmarks, since all paths have to be taken in consideration def run[VD, ED: ClassTag](graph: Graph[VD, ED]): Int = { val spGraph = graph.mapVertices { (vid, _) => makeMap(vid -> 0) } val initialMessage:SPMap = makeMap() def vertexProgram(id: VertexId, attr: SPMap, msg: SPMap): SPMap = { addMaps(attr, msg) } def sendMessage(edge: EdgeTriplet[SPMap, _]): Iterator[(VertexId, SPMap)] = { // added the concept of updating the dstMap based on the srcMap + 1 val newSrcAttr = incrementMap(edge.dstAttr) val newDstAttr = incrementMap(edge.srcAttr) List( if (edge.srcAttr != addMaps(newSrcAttr, edge.srcAttr)) Some((edge.srcId, newSrcAttr)) else None, if (edge.dstAttr != addMaps(newDstAttr, edge.dstAttr)) Some((edge.dstId, newDstAttr)) else None ).flatten.toIterator } val pregel = Pregel(spGraph, initialMessage)(vertexProgram, sendMessage, addMaps) // each vertex will contain map with all shortest paths, so just get first pregel.vertices.first()._2.values.max } } val diameter = Diameter.run(graph) 是URL参数的一部分,而应该将其作为路径的一部分。在您的示例中:http://localhost:3000/drinks/5c1b873a6a0a5d3ae0342f01?brand= ...