POST request working on Postman but not on JS - node.js

Been trying for a couple of days but can't get this request to work on NodeJS, used several request modules (axios, request, node-fetch) but the returned body is blank, same goes for postman if raw option is not selected for body.
Here is how I need to format the body on postman for the request to work:
And this is my last iteration of the request, using node-fetch:
const rawResponse = await fetch(
urlRenfe,
{
method: 'POST',
headers: {
"Cookie": cookie,
"Referer": "https://venta.renfe.com/vol/infoPuntualidadTrenes.do",
"Accept": "*/*",
},
body: `callCount=1
windowName=
c0-scriptName=infoPuntualidadTrenesSvcAjax
c0-methodName=getInfoPuntualidadTrenes
c0-id=0
c0-e1=string:71500
c0-e2=string:X7090115
c0-param0=Object_Object:{cdgoEstacion:reference:c0-e1, terminal:reference:c0-e2}
batchId=1
instanceId=1
page=%2Fvol%2FinfoPuntualidadTrenes.do
scriptSessionId=6ngaztWVMGx8q6B16ABXAlLU1Om/LwA22Om-u7tpxIlXl`
}
);
const response = await rawResponse.text();
I know 100% the headers, url and method are ok, it has to be the body, either on the library or my configuration for it.
Thanks a lot if you give me a hint on how to solve this.

Related

Spotify API POST Request - Add Tracks to Playlist: Items Not Added In Order

This is my fetch request code: (which works fine BUT the songs are not added in the order that they are in in the trackIdArr state).
// Add tracks to playlist
await fetch(
`https://api.spotify.com/v1/playlists/${playlistId}/tracks`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
body: JSON.stringify({ uris: trackIdArr }),
}
);
Spotify API doc reads:
If [position query is] omitted, the items will be appended to the playlist. Items are added in the order they are listed in the query string or request body.
How can I fix this? I have tried using for of loop, axios, adding a position parameter but it seems as though since it is an async await request, the items would not be added in order. So, why does spotify claim that it would? Am I doing something wrong? Thank you!

Posting form data with fetch api

I'm trying to post formdata with help of fetch api. Code :
var formData = new FormData();
formData.append("nickname", "johxns");
formData.append("password", "john_password");
formData.append("email", "john#server.com");
fetch("http://example/page", {
body: formData,
method: "post"
})
But in backend I'm recieving empty req body { }.
An object can be posted but why can't I post form data.
How to get this form data in backend.
You need to tell that you are sending form data not just body.
Add
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},

Body of a request is empty [duplicate]

I have a React application where I am changing POST method to GET with the request body as it is. It works fine with POST request however when I change the method to GET, it gives me error-
message: "org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public
My Front End Code-
export const setData = (getData) => dispatch => {
axios({
method: 'GET',
url: 'http://localhost:8080/api',
headers: {
'Content-Type': 'application/json'
},
data: getData
})
.then (response => {
dispatch({
type: API_DATA,
payload: response.data
})
dispatch({
type: SET_SEARCH_LOADER,
payload: false
})
})
.catch(function(error) {
})
}
Can someone let me know what I am missing here. As per my understanding, http allows to have a request body for GET method.
As per my understanding, http allows to have a request body for GET method.
While this is technically true (although it may be more accurate to say that it just doesn't explicitly disallow it), it's a very odd thing to do, and most systems do not expect GET requests to have bodies.
Consequently, plenty of libraries will not handle this.
The documentation for Axois says:
// `data` is the data to be sent as the request body
// Only applicable for request methods 'PUT', 'POST', and 'PATCH'
Under the hood, if you run Axios client side in a web browser, it will use XMLHttpRequest. If you look at the specification for that it says:
client . send([body = null])
Initiates the request. The body argument provides the request body, if any, and is ignored if the request method is GET or HEAD.
If you want to send parameters with get request in axios, you should send parameters as params.
If you want to set "Content-type":"application/json" and send params with get request, you should also send an empty data object.
For example:
const AUTH_TOKEN = 'Bearer token'
const config = {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': AUTH_TOKEN,
},
data: {},
params: {
"post_id": 1
}
}
axios.get("http://localhost/api/v1/posts/", config)
This is not axios, the error origniates from the java backend you're talking to. The public field in your request body is missing.
If you just want to send the data as parameters (which would be odd), pass it using params instead of data (as shown here: https://github.com/axios/axios#example).
I personally don't think your API should support GET with a request body (talk to the devs and ask for documentation).

Axios GET request sends empty req.body to server

I'm trying to make a GET request in my React app but Axios seems to send an empty request body for some reason. I know there's (most likely) nothing wrong in the backend as I'm able to make the requests perfectly fine with Insomnia. I've tried the following till now and none of the seem to work:
const response = await axios.get(URL, { email })
const response = await axios({
method: "get",
url: URL,
data: { email }
})
I'm using the express.json() middleware in the backend.
From the RFC 7231
A payload within a GET request message has no defined semantics;
sending a payload body on a GET request might cause some existing
implementations to reject the request.
So do not rely on body data for GET request and use appropriate HTTP method like POST, PUT etc.
Moreover, if you want to send Query params with your GET request, both code snippets you shared above will not work. Instead do it like below.
// using get method
const response = await axios.get(URL, {
params: {
ID: 12345
}
});
// using Axios API
const response = await axios({
method: "get",
url: URL,
params: {
ID: 12345
}
});

Request with request-promise and multipart/form-data

I have to implement the following workflow:
Make request no.1, get a JSON response. Manipulate this JSON object so that it can be used as payload in the second request. Make second request.
The first request is successfully implemented. I get the correct JSON object. The manipulation part is also done and tested.
I managed to create a correct postman collection for the second request. It uses the method POST, has several headers, Content-type is multipart/form-data and the payload from request no.1 is sent as Raw (in the body, options none, form-data etc ... I choose raw).
I am trying to implement this second request but get an error no matter what I try to tweak. The following is my code:
const manipulatedObject = await this._flattenPayload(payload);
const Request = require(request-promise);
const options = {
method: 'POST',
uri: 'https://second_request_url',
formData: {
file: {
value: manipulatedObject,
},
},
headers: {
Accept: 'application/json, text/plain, */*',
Connection: 'keep-alive',
'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundaryxxxxxxxxxxxxxxxx', // this is generated dynamically and matches the value in the manipulatedObject
cookie: this.cachedCookie,
'X-XSRF-TOKEN': this.cachedToken,
},
};
Request(options)
.then((body) => {
return body;
})
.catch((error) => {
return error;
});
* The parameter payload is the response from the first request.
The error I get is this:
message=source.on is not a function, stack=TypeError: source.on is not
a function
The variable manipulatedObject is a string. Currently I am copying it's value from the successful postman request to avoid errors from the manipulation process. The random token in the Content-Type header matches the ones in the manipulatedObject string. So the data are identical to the ones I use in the postman request.
I suspect the error is in the way I send the data, but I am having trouble figuring it out. I have read about this error and it seems to be generated when an object is passed to formData, but I am sending a string so I don't understand why it happens.
The values of formData accepts only three types of elements viz. string, Buffer and Stream. Refer to:request/issues/2366
U may change formData as follows:
formData: {
file: manipulatedObject,
},
or
formData: {
file: {
value: manipulatedObject,
options: {},
},
},

Resources