Posting form data with fetch api - node.js

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",
},

Related

Grabbing an image from a URL, then passing it to an API as a file in multipart form data

So I have a URL that contains an image, and I want to pass that image as part of multipart form data to an API (to be specific, if it matters, the ClickUp API). I'm doing all of this inside of a Figma plugin, which is a browser environment.
The url looks something like https://s3-alpha-sig.figma.com....
The request works perfectly for a local image that I add manually, such as in Postman. Here is the code for a successful Postman request to this endpoint:
var axios = require('axios');
var FormData = require('form-data');
var fs = require('fs');
var data = new FormData();
data.append('attachment', fs.createReadStream('7UI7S5-pw/fdb54856-9c05-479f-b726-016ef252d9f5.png'));
data.append('filename', 'example.png');
var config = {
method: 'post',
url: 'https://api.clickup.com/api/v2/task/2phh5bf/attachment',
headers: {
'Authorization': '(my auth token)',
...data.getHeaders()
},
data : data
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
However, I don't have access to local files and need to upload from a URL, so here's what I've done so far:
var data = new FormData();
data.append('attachment', open(imgURL));
data.append('filename', 'screenshot.png');
fetch(`(the URL)`, {
"method": "POST",
"muteHttpExceptions": true,
"headers": {
'Authorization': '(my auth token)',
...data.headers
},
data: data
}).then(response => {
console.log(response)
})
How should I be converting the URL into something I can input as Form Data? Thanks so much in advance!

How can i pass authroziation token in header with multipart/form-data

I am using reactjs in my front end, so I am converting an image into base64 data and pass it to nodejs, In my backend I am trying send the base64 data to 3rd part API using fetch call, But it returns
401 unauthorization error
If I pass authorization in header nothing happens
const formData = new FormData();
formData.append('file', url);
const resp = await fetch(requestURL, {
method: 'POST',
headers: {
'Authorization': accessToken,
'Content-Type': 'multipart/form-data',
},
body: formData,
});
Can anyone help me with this?

POST request working on Postman but not on 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.

Making a POST request using puppeteer with JSON payload

I'm trying to make a POST request using puppeteer and send a JSON object in the request, however, I'm getting a timeout... if I'm trying to send a normal encoded form data that at least a get a reply from the server of invalid request...
here is the relevant part of the code
await page.setRequestInterception(true);
const request = {"mac": macAddress, "cmd": "block"};
page.on('request', interceptedRequest => {
var data = {
'method': 'POST',
'postData': request
};
interceptedRequest.continue(data);
});
const response = await page.goto(configuration.commandUrl);
let responseBody = await response.text();
I'm using the same code to make a GET request (without payload) and its working
postData needs to be encoded as form data (in the format key1=value1&key2=value2).
You can create the string on your own or use the build-in module querystring:
const querystring = require('querystring');
// ...
var data = {
'method': 'POST',
'postData': querystring.stringify(request)
};
In case you need to submit JSON data:
'postData': JSON.stringify(request)
If you are sending json, you need to add "content-type": "application/json". If you don't send it you can receive an empty response.
var data = {
method : 'POST',
postData: '{"test":"test_data"}',
headers: { ...interceptedRequest.headers(), "content-type": "application/json"}
};
interceptedRequest.continue(data);

Microsoft Translator Api in JSON format

How can I use Microsoft.Translator.TranslateArray method in Node.js to send and receive data in JSON format as XML not allow\u001b etc. unicode. I am sending JSON request but getting this error:
"ArgumentOutOfRangeException: 'to' must be a valid language\u000d\u000aParameter >name: to : ID=5639.V2_Json.TranslateArray.12E99F9A"
You can use REST API to translate array of texts
POST http://api.microsofttranslator.com/V2/Http.svc/TranslateArray
Check the reference for details
you can use request module to hit this API.
Example:
var request = require('request');
request({
method: 'POST',
url: 'http://api.microsofttranslator.com/V2/Http.svc/TranslateArray',
headers: {
Authorization: 'Bearer *********' //put accesstoken
},
json: data //put your JSON here
}, function(err, res, body) {});

Resources