简体   繁体   English

未收到 JavaScript 获取请求正文参数

[英]JavaScript fetch request body parameters not received

Context: I am trying to send a put request to a server using JavaScript and fetch from an html file I'm writing.上下文:我正在尝试使用 JavaScript 向服务器发送放置请求,并从我正在编写的 html 文件中获取。

Problem: The request I made is working in Insomnia, but when I try to send it from an html it isn't properly received.问题:我提出的请求在 Insomnia 中有效,但是当我尝试从 html 发送它时,它没有被正确接收。 The code was generated by Insomnia also.该代码也是由 Insomnia 生成的。 When I send it from the html the request is sent, and I get an ok back, but the server doesn't complete the task in the request, leading me to believe that it wasn't received or I missed something.当我从 html 发送请求时,请求被发送,我得到了一个好的回复,但服务器没有完成请求中的任务,这让我相信它没有收到或者我错过了一些东西。 When trying to send the request, the console shows a response, that says "ok", 200, etc., but also has a "bodyUsed: false" part.尝试发送请求时,控制台会显示响应,表示“ok”、200 等,但还有“bodyUsed: false”部分。

The function generated by Insomnia: Insomnia 生成的函数:

 fetch("url", { "method": "PUT", "headers": { "content-type": "application/x-www-form-urlencoded" }, "body": { "name": "name", "desc": "description" } }) .then(response => { console.log(response); }) .catch(err => { console.log(err); });

Question(s): Is there anything wrong with the code?问题:代码有问题吗? How does the server receive the request but not the body?服务器如何接收请求而不是正文? Does the "bodyUsed: false" message mean that the request's body was ignored for some reason? “bodyUsed: false”消息是否意味着由于某种原因忽略了请求的正文? Could this all be the server's fault?难道这一切都是服务器的错?

Disclaimer: I am a bit new to web development, so forgive me if I miss some obvious point.免责声明:我对 Web 开发有点陌生,所以如果我错过了一些明显的点,请原谅我。

If you keep "content-type": "application/x-www-form-urlencoded" and your server is configured that way, you should send your data using a FormData like this:如果你保持"content-type": "application/x-www-form-urlencoded"并且你的服务器是这样配置的,你应该使用这样的FormData发送你的数据:

var formData = new FormData(); 
formData.append('name', 'Chris');
formData.append('descr', 'description');

fetch("url", {
  "method": "PUT",
  "headers": {
    "content-type": "application/x-www-form-urlencoded"
  },
  "body": formData
})
.then(response => {
  console.log(response);
})
.catch(err => {
  console.log(err);
});

try this尝试这个

let formData = new FormData();

formData.append('name', 'name value');
formData.append('desc', 'description value');

fetch('url', {
    method: 'POST',
    credentials: 'same-origin',
    body: formData
}).then(rawResponse => rawResponse.json())// or rawResponse.text() to get simple string
        .catch(error => {
            console.log(error);
        })
        .then(response => {
            console.log(response);
        });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM