[英]Javascript REST API with body in GET
I'm working in Javascript (frontend) and have a colleague working in the backend with NodeJS.我在 Javascript(前端)工作,有一个同事在后端使用 NodeJS。 When calling a GET request , he asks me to put the data in the body , but I could not figure out how to do that.
在调用 GET 请求时,他要求我将数据放入 body 中,但我不知道该怎么做。 (If I use this code to a POST request, it works fine).
(如果我将此代码用于 POST 请求,则它工作正常)。 Could you tell me if this is possible and how to do it?
你能告诉我这是否可能以及如何做到这一点? He says that it is possible, but I've googled a lot and could not find the correct way to do that.
他说这是可能的,但我在谷歌上搜索了很多,找不到正确的方法来做到这一点。 ERROR that I get: "Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body."
我得到的错误: “无法在 'Window' 上执行 'fetch':使用 GET/HEAD 方法的请求不能有正文。”
let URL = "http://localhost:3000/verifyUser";
let token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI2NjJDMTRBNk";
fetch(URL, {
method: request,
mode: 'cors',
body: JSON.stringify({
user: 'Carlos6',
password: '543534543',
email: "algo6@gmail.com"
}),
headers: {
'Accept' : 'application/json',
'Content-type': 'application/json; charset=UTF-8',
'auth-token': token
}
}).then(function (response) {
if (response.ok) {
return response.json();
}
return Promise.reject(response);
}).then(function (data) {
console.log(data);
}).catch(function (error) {
console.warn('Something went wrong.', error);
});
You are using HTTP GET and sending a body.您正在使用 HTTP GET 并发送正文。
If you want to send a body (JSON) you should use the PUT and POST.如果要发送正文 (JSON),则应使用 PUT 和 POST。
The best will probably be to:最好的可能是:
method: "PUT"
method: "PUT"
If you want to know which one to chose look at this question: ( PUT vs. POST in REST )如果您想知道选择哪一个,请查看这个问题:( REST 中的 PUT 与 POST )
If you wish to send a request with a body then you should make a POST-request and not a GET one.如果你想发送一个带有正文的请求,那么你应该发出一个 POST 请求而不是一个 GET 请求。 GET-request cannot have a body by its nature and primary goal.
GET 请求不能有其性质和主要目标的主体。 All params of GET-request must be indicated in the URL itself only.
GET-request 的所有参数必须仅在 URL 本身中指明。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.