在POST中提供Content-length标头时,REST API响应带有400错误的请求

时间:2018-12-28 18:02:30

标签: api post xmlhttprequest http-headers

我有一个网站和一个python flask RESTFUL API。用Postman测试API时,它的工作原理很好,但是在js中使用XMLHttprequest的相同请求给了我400错误的请求代码。我查看了邮件头,并在Postman中复制了XMLHttprequest邮件头,以获得400 BAD REQUEST代码。如果我从请求中删除Content-Length标头,则可以正常工作。我的邮递员代码(HTML,没有内容长度):

POST /user/181453766040485888 HTTP/1.1
Host: 127.0.0.1:5000
Content-Type: multipart/form-data; boundary=--- 
-WebKitFormBoundary7MA4YWxkTrZu0gW
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Connection: keeep-alive
Host: 127.0.0.1:5000
Origin: http://localhost:52014
Referer: http://localhost:52014/settings.php
User-Agent: Mozilla/5.0 (Windows NT 10.0; 
Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 OPR/57.0.3098.106 (Edition Campaign 76)
cache-control: no-cache
Postman-Token: 5dd34b0b-965c-4d31-83b9-2364b03c0aa2

Content-Disposition: form-data; name="status"

0

Content-Disposition: form-data; name="username"

0

Content-Disposition: form-data; name="token"

0

Content-Disposition: form-data; name="display_names"

1

Content-Disposition: form-data; name="messages"

1

Content-Disposition: form-data; name="roles"

1

Content-Disposition: form-data; name="votes"

1
------WebKitFormBoundary7MA4YWxkTrZu0gW--

我的js函数(用于测试):

function save() {
        var formData = new FormData();
        formData.append("status", 0);
        formData.append("username", 0);
        formData.append("token", 0);
        formData.append("display_names", 0);
        formData.append("messages", 0);
        formData.append("roles", 0);
        formData.append("votes", 0);

        const Http = new XMLHttpRequest();
        const url='http://127.0.0.1:5000/user/181453766040485888';
        Http.open("POST", url);
        Http.onreadystatechange=(e)=>{
            console.log(Http.responseText)
        }
        Http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        Http.send(formData);
    }

我处理请求的API函数(抽象):

def post(self, id):
    if database.execute(database.SAVE_USER_SETTINGS.format(id, request.form["status"], request.form["username"],
                                                        request.form["token"], request.form["display_names"],
                                                        request.form["messages"], request.form["roles"],
                                                        request.form["votes"])):
        return (id, request.form["status"], request.form["username"],
                    request.form["token"], request.form["display_names"],
                    request.form["messages"], request.form["roles"],
                    request.form["votes"]), 201

    return {}, 500

0 个答案:

没有答案