Send request with equivalent to Python's bytes() in Node.js - node.js

I'm looking to send a request in Node.js which requires sending the data in byte format.
In python, I've implemented it as follow:
r = requests.post(url="https://example.com",headers=headers, data=bytes(exampleArray))
The type of exampleArray is uint8 array
Is it possible to do this same post in Node.js, potentially with axios or another module?

Axios accepts a variety of formats as payload. This is an example with an Uint8Array array:
const axios = require('axios');
const data = new TextEncoder().encode(
JSON.stringify({
foo: 'bar',
})
);
axios
.post('http://localhost:3001', data)
.then((res) => {
console.log(`Status: ${res.status}`);
console.log('Body: ', res.data);
})
.catch((err) => {
console.error(err);
});
The same applies to the http(s) module
const http = require('http');
const data = new TextEncoder().encode(
JSON.stringify({
foo: 'bar',
})
);
const options = {
hostname: 'localhost',
port: 3001,
path: '/',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': data.length,
},
};
const req = http.request(options, (res) => {
console.log(`statusCode: ${res.statusCode}`);
res.on('data', (d) => {
process.stdout.write(d);
});
});
req.on('error', (error) => {
console.error(error);
});
req.write(data);
req.end();

Related

How to send the result of a GET request in a POST request?

I need to send a GET request to https://random.dog/woof.json. It generate a random image and returns a json like this {
"fileSizeBytes": 1133380,
"url": "https://random.dog/8aff4e84-260d-4af0-9dc1-438d07ba3884.jpg"
} and I need save an image to my database. How can I take "url" and send it with POST request?
you can use node-fetch for server side requests.
It's similar to js' fetch api:
const fetch = require('node-fetch');
fetch('https://random.dog/woof.json')
.then(res => res.json())
.then(json => {
console.log("URL:", json[0].url);
fetch('<url for your post request>', {
method: 'POST',
body: { url: json[0].url },
headers: { 'Content-Type': 'application/json' }
}).then(postRes => postRes.json())
.then(postJson => console.log(postJson));
})
You can do something like that
const https = require('https')
function getData(url: String) {
const options = {
hostname: 'exemple.com',
path: '/your-endpoint',
method: 'POST',
headers: {
'Content-Type': 'application/json',
}
}
const req = https.request(options, (response: any) => {
let body = '';
response.on("data", (data: String) => {
body += data;
})
response.on("end", () => {
console.log(body)
})
response.on("error", (error: String) => {
console.error(error)
})
})
req.write(JSON.stringify({
url
}));
req.end()
}
https.get("https://random.dog/woof.json", (response: any) => {
let body = '';
response.on("data", (chunk: String) => {
body += chunk;
})
response.on("end", () => {
const obj = JSON.parse(body);
getData(obj.url)
})
});

NodeJS request get return me html code instead of json

I'm trying to get get a json from a get request it's work in python but in NodeJs that display me the html code source of the page
this is my code :
app.get("/well", function(request, response) {
const req = require('request');
const options = {
url: 'https://swarmmanager.francecentral.cloudapp.azure.com:3000',
method: 'GET',
headers: {
'Accept': 'application/json',
},
agentOptions: {
ca: fs.readFileSync("public/IdaktoPKIRootCA.crt")
}
};
req(options, function(err, res, body) {
console.log(body);
});
});
and this is another version but same problem:
app.get("/well", function(request, response) {
g_CnieOidcAddr = 'https://swarmmanager.francecentral.cloudapp.azure.com:3000';
const options = {
hostname: 'swarmmanager.francecentral.cloudapp.azure.com',
port: 3000,
method: 'GET',
headers: {
'Accept': 'application/json',
},
ca: fs.readFileSync("public/IdaktoPKIRootCA.crt")
};
const req = https.request(options, (res) => {
console.log('statusCode:', res.statusCode);
console.log('headers:', res.headers);
res.on('data', (d) => {
process.stdout.write(d);
});
});
req.on('error', (e) => {
console.error(e);
});
req.end();
});
i try to do it in python and it's work find that return me a json:
headers = {'Accept': 'application/json'}
r = requests.get(g_CnieOidcAddr + '/.well-known/openid-configuration', params={}, headers = headers, verify='./IdaktoPKIRootCA.crt')
print (r.text)
if anyone has an idea i'm a taker ^^ thanks for reading.
ok that work find i just forgot something at the end of the url so if you come to this page the 2 codes work find to to a request

error using nodejs to do http post request

I have followed some instructions to do http request in nodejs and I am doing it in TypeScript in the following way:
code that calls the function to do http post call:
const getCaseInfoRequest: GetCaseInfoRequest = {
emailAddress: 'some-email-address#amazon.com'
};
makeCardinalCall('/SalesforceCaseService/1.0/GetCaseInfoFromEmail', getCaseInfoRequest, process.env.STAGE)
.then((data) => {
...
}).catch(...);
the function that does http post call:
export function makeCardinalCall(path: string, requestBody: GetCaseInfoRequest, stage?: string) {
return new Promise((resolve, reject) => {
const data = JSON.stringify(requestBody);
const options: http.RequestOptions = {
host: 'my-service.google.com',
port: 443,
path: path,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': data.length,
}
};
const req = http.request(options, (res: http.IncomingMessage) => {
res.setEncoding("utf8");
let data = '';
res.on('data', chunk => {
data += chunk;
});
res.on('end', () => {
resolve(data);
})
});
req.on('error', (e: any) => {
reject(e);
});
req.end(data);
});
}
but i always got the following error:
{"bytesParsed":0,"code":"HPE_INVALID_CONSTANT","reason":"Expected HTTP/","rawPacket":{"type":"Buffer","data":[21,0,0,0,2,1,0]}}
any hint / help would be greatly appreciated!
You're attempting to use the raw http module with an HTTPS endpoint (as evident from the port 443). The HTTP parser fails to parse the TLS bytes coming over the wire.
For your own sanity's sake, use a wrapper module for requests -- such as node-fetch...

How can I get Axios to send a request with FormData?

I'm unable to get the server that I'm calling to recognize the FormData that I'm providing when I use axios. It keeps telling me that I'm not providing the right FormData even though it works in Postman and Node native http (see below):
import { Router } from "express";
import axios from "axios";
import * as FormData from "form-data";
const router = Router();
const cookieHeader = {
Cookie: "XXX",
};
router.get("/", async (_req, res) => {
try {
const formData = new FormData();
formData.append("key1", JSON.stringify(["value1"]));
formData.append("key2", "value2");
formData.append("key3", "value3");
const response = await axios.post("https://xxx", formData, { headers: { "Content-Type": "multipart/form-data; boundary=--------------------------811161660471543283806813" } });
res.send(response.data);
} catch (error) {
console.log(error);
}
});
module.exports = router;
I am able to get it working in Postman and used that to export using Node's native http, which also works:
import { Router } from "express";
import { https } from "follow-redirects";
const router = Router();
router.get("/", () => {
const options = {
method: "POST",
hostname: "xxx",
path: "/xx/xxx",
headers: {
"Content-Type": "multipart/form-data; boundary=--------------------------811161660471543283806813",
Cookie: "xxx",
},
maxRedirects: 20,
};
const req = https.request(options, (res: any) => {
const chunks: any[] = [];
res.on("data", (chunk: any) => {
chunks.push(chunk);
});
res.on("end", () => {
const body = Buffer.concat(chunks);
console.log(body.toString());
});
res.on("error", (error: any) => {
console.error(error);
});
});
const postData = `------WebKitFormBoundary7MA4YWxkTrZu0gW\nContent-Disposition: form-data; name=\"key1\"\n\n[\"value1\"]\n------WebKitFormBoundary7MA4YWxkTrZu0gW\nContent-Disposition: form-data; name=\"key2\"\n\nvalue2\n------WebKitFormBoundary7MA4YWxkTrZu0gW\nContent-Disposition: form-data; name=\"key3\"\n\nvalue3\n------WebKitFormBoundary7MA4YWxkTrZu0gW--`;
req.setHeader("content-type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW");
req.write(postData);
req.end();
});
module.exports = router;
I figured it out after reading through https://github.com/axios/axios/issues/318. It wasn't until near the end that Googrosh posted that he used .getHeaders(). Lo and behold, I added that to my headers too and it worked.
So updating my code, here's what it looks like:
const response = await axios.post("https://xxx", formData, { headers: formData.getHeaders() });
onst formUrlEncoded = x =>
Object.keys(x).reduce((p, c) => p + `&${c}=${encodeURIComponent(x[c])}`, '')
var axios = require("axios");
axios({
url: 'https://login.xyz.com/oauth/v2/token',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
data: formUrlEncoded({
client_id: '***',
client_secret: '***',
grant_type: 'authorization_code',
})
})
.then(function(response) {
console.log(response.data)
})
.catch(function(error) {
console.log(error)
})

How to add JSON data in a http post request in AWS lambda?

const http = require('http');
exports.handler = function(event, context) {
var url = event && event.url;
http.post(url, function(res) {
context.succeed();
}).on('error', function(e) {
context.done(null, 'FAILURE');
});
};
I am using this in my AWS lambda code to send http request.
I have a JSON file that has to be sent as a part of this post request.
How to add JSON ? Where do I specify ?
If you are asking from where to pickup that json file form, then s3 would be the correct place to put that file and read form the lambda and do a post.
const obj= {'msg': [
{
"firstName": "test",
"lastName": "user1"
},
{
"firstName": "test",
"lastName": "user2"
}
]};
request.post({
url: 'your website.com',
body: obj,
json: true
}, function(error, response, body){
console.log(body);
});
With just http
const postData = querystring.stringify({
'msg': 'Hello World!'
});
const options = {
hostname: 'www.google.com',
port: 80,
path: '/upload',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(postData)
}
};
const req = http.request(options, (res) => {
console.log(`STATUS: ${res.statusCode}`);
console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
res.setEncoding('utf8');
res.on('data', (chunk) => {
console.log(`BODY: ${chunk}`);
});
res.on('end', () => {
console.log('No more data in response.');
});
});
req.on('error', (e) => {
console.error(`problem with request: ${e.message}`);
});
// Write data to request body
req.write(postData);
req.end();

Resources