I need to use http internal NodeJS library to make a POST request, how can i attach body object with this request? When I'm looking into http.RequestOptions I don't see any data or body property :/
import * as http from "http";
const options2: http.RequestOptions = {
hostname: 'www.google.com',
port: 80,
path: '/upload',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(null)
},
};
http.request(options, (res: http.IncomingMessage) => {
});
thanks for any help!
http.request returns an http.ClientRequest object.
You need to call the write method on that and pass in your body data.
Related
I have an HTTP POST request that accepts the body as form-data.
grant_type: client_credentials
when I use this API in an application, I need to pass a client_id and client_secret parameter to this call.
so far I have
const postRequest = {
url: 'https://address',
method: 'POST',
headers: {
'authorization': 'Basic xyz',
'content-type': 'application/x-www-form-urlencoded'
},
formData: {
'grant_type': 'client_credentials'
}
};
How do I include the id and secret into this request?
I have also tried
formData: {
'grant_type' : 'client_credentials',
'client_id' :'id',
'client_secret' : 'secret'
}
that does not work either as stated in How to use FormData for AJAX file upload?
This is an OAuth2 flow, and it's most likely you need to pass this in your Basic authorization header.
headers: {
'authorization': 'Basic ' + btoa(`${clientId}:${clientSecret}`),
'content-type': 'application/x-www-form-urlencoded'
},
It's even better to use a good existing OAuth2 library to handle the heavy lifting. I've open sourced mine:
https://github.com/badgateway/oauth2-client
it would work like this:
const client = new OAuth2Client({
tokenEndpoint: 'https://address',
clientId: '...',
clientSecret: '...',
});
const result = await client.clientCredentials();
whats up!
i am trying to send a request with json parameters and i don't understand why in the server side
the parameter doesn't being send
let res = fetch("http://localhost:1000/vacations/" + vacation.id, {
method: "DELETE",
headers: { "Authorization": localStorage.token },
body: { "picture": vacation.picture }
})
i am trying to view the picture in the parameter in the server side
i use in node.js server the middleware express.json
and still i cant get this parameter :(
You may send a stringify body using JSON.stringify.
const res = fetch(`http://localhost:1000/vacations/${vacation.id}`, {
method: "DELETE",
headers: {
Authorization: localStorage.token
},
body: JSON.stringify({
picture: vacation.picture
})
})
I mean, i'm trying to make the most simple upload ever, with the following code:
var http = require('http');
var request = http.request({
method: 'post',
host: 'https://www.ws-ti.4bank.com',
path: '/img/create_file',
headers: form.getHeaders()
});
form.pipe(request);
request.on('response', function(res) {
console.log(res.statusCode);
});
The point is, if i make a post like this, what it'll post exacly?
Does i need to put at least one header parameter or this create some kind of template?
If i need to put at least one parameter, i would put it into the form.getHeaders"()"?
Through headers you should send HTTP headers of the request as an object
Example code:
var request = http.request({
method: 'post',
host: 'https://www.ws-ti.4bank.com',
path: '/img/create_file',
headers: {
'Accept': 'text/html',
}
});
full list of the header can be found here
You can send data as JSON with the request as follows:
const data = JSON.stringify({
text: 'Hello World'
});
request.write(data);
request.end();
I'm getting this error coming from my require.post(error)
its a lambda function deployed from a vagrant box. It is a wrapper for an api, the event.body has the properly formatted post json and everything is working perfectly when the post is done from postman. I have seen a roughly similar problem solved by
npm config set proxy http://usr:pwd#host:port
npm config set https-proxy http://usr:pwd#host:port
Please help! : )
Error: Invalid protocol: undefined
at Request.init (/var/task/node_modules/request/request.js:454:31)
at new Request (/var/task/node_modules/request/request.js:127:8)
at request (/var/task/node_modules/request/index.js:53:10)
at Function.post (/var/task/node_modules/request/index.js:61:12)
at module.exports.startVerifyProcess (/var/task/handler.js:83:13)
my Code:
module.exports.startVerifyProcess = (event, context, callback) => {
var body = JSON.parse(event.body);
const params = querystring.parse(event.body);
console.warn(body);
var Re;
var post_options = {
host: 'api.demo.veri.com',
path: '/api/v1/verify/requests',
port: 443,
method: 'POST',
headers: {
// 'Content-Type': 'application/json',
// 'Content-Length': Buffer.byteLength(event.body),
"Authorization": "myValidAuth",
},
}
request.post(post_options, body, function(err, res, resBody) {
if (err){
console.error(err);
}
console.warn("RESPONSE " + resBody);
});
callback(null, {
statusCode: 200,
body: JSON.stringify({
body: Re
})
});
}
The issue here is that request should not take the body as the second parameter.
request.post(post_options, function(err, res, resBody) is correct and the body should be in the post_options object. While your at it chose either camelCase or snake_case for everything in that project. Also check out node-fetch I would consider it a solid upgrade from using request.
My RESTful service allows batching requests.
I'm trying to combine requests into one batch with help of Fetch API:
let req1 = {
url: "/cups/count",
options: {
method: 'GET',
headers: {
'Content-Type': 'application/http'
}
}
},
req2 = {
url: "/spoons/count",
options: {
method: 'GET',
headers: {
'Content-Type': 'application/http'
}
}
},
authToken = "Bearer my_token123",
batchUrl = "http://something.com/batch",
options = {
method: 'POST',
headers: {
'Authorization': authToken,
'Content-Type': 'multipart/mixed'
},
body: {req1, req2}
};
return fetch(batchUrl, options)
.then(response => response.json())
.then(items => dispatch(batchSuccess(items)))
.catch((err) => {
console.log(err)
});
However it returns an error - bad request. I suppose I may combine HTTP requests in wrong way.
Is there simpler way of doing this?
Where in Network Chrome Dev Tools can I see nested HTTP requests?
Your code does not work because it does not follow multipart/mixed request format:
In Content-Type header, there is no boundary information.
The child requests are not divided by boundary, instead they will be sent as plain text of req1 & req2 object.
In order to send valid multipart/mixed request, there is a node.js module batchelor. According to the introduction page, its usage is pretty simple.
If you want to send multipart/mixed request from browser, you can use build tool (gulp, webpack etc.) to compile batchelor into something like "batchelor-compiled.js" and import it in HTML.
For developer tool, I didn't find anything in Chrome, but the child requests are visible in Firefox debug window's "Params" tab.
Here is an example of a batch request using the Fetch API with the Gmail Batch REST API.
This will get the content of several messages at once.
const response = await fetch("https://www.googleapis.com/batch/gmail/v1", {
headers: {
"Content-Type": "multipart/mixed; boundary=batch_boundary",
Authorization: "Bearer <access_token>",
},
method: "POST",
body: `--batch_boundary
Content-Type: application/http
Content-ID: 1
GET /gmail/v1/users/me/messages/{message-id-1}
--batch_boundary
Content-Type: application/http
Content-ID: 2
GET /gmail/v1/users/me/messages/{message-id-2}
--batch_boundary--`,
});
console.log(await response.text());