简体   繁体   中英

Javascript REST API with body in GET

I'm working in Javascript (frontend) and have a colleague working in the backend with 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. (If I use this code to a POST request, it works fine). 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."

    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.

If you want to send a body (JSON) you should use the PUT and POST.

The best will probably be to:

  • change your client code to method: "PUT"
  • change the server to access PUT request

If you want to know which one to chose look at this question: ( PUT vs. POST in REST )

If you wish to send a request with a body then you should make a POST-request and not a GET one. GET-request cannot have a body by its nature and primary goal. All params of GET-request must be indicated in the URL itself only.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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