I'm using https for this POST request.
Could someone point out the issue here? I get undefined and no error message .
I tried wrapping the request before res.write with no success. I'm getting a
statusCode: 400
Bad Payload received by generic incoming webhook.
Thanks!
connector.js
const https = require('https');
var dataString = {"text": "Hello World"};
const deets = {
portal_trade_events: {
host: "outlook.office.com",
path: "/path",
headers: {
'Content-Type': 'application/json',
'Content-Length': dataString.text.length
}
}
};
const options = {
hostname: deets.portal_trade_events.host,
port: 443,
path: deets.portal_trade_events.path,
method: 'POST',
headers: deets.portal_trade_events.headers
};
function post(options, data) {
const req = https.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(JSON.stringify(data));
req.end()
}
post(options, dataString);
At the very least, your headers for content-length look wrong. You're sending the full JSON, not just the one text value.
const https = require('https');
const data = JSON.stringify({
text: 'Hello World'
});
const options = {
hostname: 'outlook.office.com',
port: 443,
path: '/path',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': data.length
}
};
const req = https.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
I have a Vue 3 + node express back-end server + firebase.
On my backend server, the middleware:
const getAuthToken = (req, _, next) => {
if (
req.headers.authorization &&
req.headers.authorization.split(" ")[0] === "Bearer"
) {
req.authToken = req.headers.authorization.split(" ")[1];
} else {
req.authToken = null;
}
next();
};
const checkIfAuthenticated = (req, res, next) => {
getAuthToken(req, res, async() => {
try {
const { authToken } = req;
const userInfo = await admin.auth().verifyIdToken(authToken);
req.authId = userInfo.uid;
return next();
} catch (e) {
return res
.status(401)
.send({ error: "You are not authorized to make this request" });
}
});
};
The /get routes using the middleware
router.get('/bearer', checkIfAuthenticated, async function(req, res) {
res.send('Bearer test');
})
App using the following path on port 3000:
app.use('/users', userRoute);
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
In front-end i want to make the api call for /users/bearer path but i'm still unaunthorized after passing the token in header:
In browser front-end client I'm using this path: http://localhost:8080/users/bearer
async accesPrivateData() {
const token = await firebase.auth().currentUser.getIdToken();
let config = {
headers: {
Authorization: `Bearer ${token}`
}
};
axios.get("http://localhost:3000/users/bearer",config)
.then(() => {
console.log("Am intrat");
})
.catch(function (error) {
console.log(error);
});
}
**I tried to console log the token and it's there!**
Index.js Vue router:
{
path: "/users/bearer",
name: "bearer",
component: bearer
}
the config after console log:
console.log(config);
{headers: {…}}
headers: {Authorization: "Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6IjVmOTcxMmEwODc.....
EDIT: In checkIfAuthenticated function my const { authToken } = req; is undefiend
You can try setting the authorization headers in different ways, here the 2 most common ways to do it:
with common headers:
axios.defaults.headers.common['Authorization'] = <YourToken>;
with interceptor:
axios.interceptors.request.use(
(config) => {
let token = <getyourToken>
if (token) {
config.headers['Authorization'] = `Bearer ${token}`;
}
return config;
},
(error) => {
return Promise.reject(error);
}
);
In your code you could try with common by change it to:
async accesPrivateData() {
const token = await firebase.auth().currentUser.getIdToken();
axios.defaults.headers.common['Authorization'] = `Bearer ${token}`
axios.get("http://localhost:3000/users/bearer")
.then(() => {
console.log("Am intrat");
})
.catch(function (error) {
console.log(error);
});
}
I'm having trouble receiving a simple object that's been turned into JSON. It shows up in the console.log as a {}, nothing more. I'll just refer to the server code:
const express = require("express");
const app = express();
app.listen(3000);
app.use(express.static("public"));
app.use(express.json());
app.post("/api", (request, response) => {
console.log("You got a request");
console.log(request.body);
});
And the index.html code:
console.log("geolocation available");
navigator.geolocation.getCurrentPosition((position) => {
const lat = position.coords.latitude;
const long = position.coords.longitude;
const data = { lat, long };
const options = {
method: "POST",
header: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
};
fetch("/api", options);
});
} else {
console.log("geolocation not available");
}
Thanks in advance!
You have a type in index.html, it should be "headers" not "header"
const options = {
method: "POST",
headers: { // Not header
"Content-Type": "application/json",
},
body: JSON.stringify(data),
};
Vaguely following this 'tutorial': https://stackabuse.com/the-node-js-request-module/
I get to the alert ('Options Declared'), but then my program stops at the request and I have no idea why.
const request = require('request');
function testGet(){
alert("Get test started");
const options = {
url: "https://www.reddit.com/r/funny.json",
method: 'GET',
headers: {
'Accept': 'application/json',
'Accept-Charset': 'utf-8',
'User-Agent': 'my-reddit-client'
}
}
alert("Options declared");
request(options, function(err, res, body){
let json = JSON.parse(body);
console.log(json);
});
alert("Get test done");
}
Just send the response and error as the response object and look at what comes.
const request = require('request');
function testGet(){
alert("Get test started");
const options = {
url: "https://www.reddit.com/r/funny.json",
method: 'GET',
headers: {
'Accept': 'application/json',
'Accept-Charset': 'utf-8',
'User-Agent': 'my-reddit-client'
}
}
alert("Options declared");
request(options, function(err, res, body){
res.json({err : err, result: body});
});
}
You place the request function declaration and body inside testGet().
Please do that outside the testGet() like this.
function testGet(){
alert("Get test started");
const options = {
url: "https://www.reddit.com/r/funny.json",
method: 'GET',
headers: {
'Accept': 'application/json',
'Accept-Charset': 'utf-8',
'User-Agent': 'my-reddit-client'
}
}
alert("Options declared");
request.post(options, callback);
}
request(options, function(err, res, body) {
let json = JSON.parse(body);
console.log(json);
alert("Get test done");
});
How do I properly send JSON data over Http Post on NodeJS? I have checked that the data I'm sending is definitely JSON but every time I try sending over http post, it would receive an error. I cant exactly see the error as it's returning from terminal and even if I output, it's too messy, not properly formatted
var options = {
hostname: 'www.postcatcher.in',
port: 80,
path: '/catchers/5531b7faacde130300002495',
method: 'POST',
headers: {
'Content-Type': 'application/json',
}
};
var req = http.request(options, function(res) {
console.log('Status: ' + res.statusCode);
console.log('Headers: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (body) {
console.log('Body: ' + body);
fs.writeFile("/var/www/node/test.txt", body, function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
// write data to request body
req.write('{"string": result}'); ///RESULT HERE IS A JSON
req.end();
Also tried this
// request.post(
// '',
// { form: { key: result } },
// function (error, response, body) {
// if (!error && response.statusCode == 200) {
// console.log(body);
// }
// }
// );
// console.log(result);
result is not being interpolated.
this seems to work correctly..
http = require('http');
fs = require('fs');
var options = {
hostname: 'www.postcatcher.in',
port: 80,
path: '/catchers/5531b7faacde130300002495',
method: 'POST',
headers: {
'Content-Type': 'application/json',
}
};
var req = http.request(options, function(res) {
console.log('Status: ' + res.statusCode);
console.log('Headers: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (body) {
console.log('Body: ' + body);
fs.writeFile("test.txt", body, function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
// write data to request body
// req.write('{"string": result}'); ///RESULT HERE IS A JSON
result = '{ "hello": "json" }';
req.write('{"string": '+result+'}');
req.end();
result:
$ node 29712051.js
Status: 201
Headers: {"server":"Cowboy","date":"Sat, 18 Apr 2015 04:23:52 GMT","connection":"keep-alive","x-powered-by":"Express","content-type":"text/plain","content-length":"7","set-cookie":["connect.sid=0eGSTYI2RWf5ZTkpDZ0IumOD.OrcIJ53vFcOiQSdEbWz0ETQ9n50JBnXyZRjrSyFIdwE; path=/; expires=Sat, 18 Apr 2015 08:23:53 GMT; httpOnly"],"x-response-time":"6ms","via":"1.1 vegur"}
Body: Created
The file was saved!
$ cat test.txt
Created
actually, u can use JSON.stringify(result) to instead '{"string": '+result+'}':
http = require('http');
fs = require('fs');
var options = {
hostname: 'www.postcatcher.in',
port: 80,
path: '/catchers/5531b7faacde130300002495',
method: 'POST',
headers: {
'Content-Type': 'application/json',
}
};
var req = http.request(options, function(res) {
console.log('Status: ' + res.statusCode);
console.log('Headers: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (body) {
console.log('Body: ' + body);
fs.writeFile("test.txt", body, function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
// write data to request body
// req.write('{"string": result}'); ///RESULT HERE IS A JSON
//
result = JSON.stringify({ hello: "json" });
req.write('{"string": '+result+'}');
//
req.end();
I'm looking into the most efficient way to get multiple JSON files from different API endpoints using node.
Basically i'd like to store each JSON object in a variable, and send them all to Jade template files for parsing.
I've got it setup working for getting one single JSON file (jsonFile1) by doing the following:
httpOptions = {
host: 'api.test123.com',
path : '/content/food/?api_key=1231241412',
headers: {
"Accept": "application/json",
'Content-Type': 'application/json'
},
method: "GET",
port: 80
}
var jsonFile1;
http.get(httpOptions, function(res) {
var body = '';
res.on('data', function(chunk) {
body += chunk;
});
res.on('end', function() {
jsonFile1= JSON.parse(body)
console.log("Got response: " + jsonFile1);
});
}).on('error', function(e) {
console.log("Got error: " + e.message);
});
app.set('views', __dirname);
app.get('/', function(req, res) {
res.render('home', {
data: jsonFile1
});
});
But i don't really want to have to repeat all of this to get multiple json endpoints and send them to home jade template.
Any ideas to do this efficiently?
Based on your code, this is a quick example using the excellent async library.
var async = require('async'),
// Array of apis
httpOptions = [
{
host: 'api.test123.com',
path : '/content/food/?api_key=1231241412',
headers: {
"Accept": "application/json",
'Content-Type': 'application/json'
},
method: "GET",
port: 80
},
host: 'api.test234.com',
path : '/content/food/?api_key=1231241412',
headers: {
"Accept": "application/json",
'Content-Type': 'application/json'
},
method: "GET",
port: 80
}
];
// Put the logic for fetching data in its own function
function getFile(options, done) {
http.get(options, function(res) {
var body = '';
res.on('data', function(chunk) {
body += chunk;
});
res.on('end', function() {
done(null, JSON.parse(body));
console.log("Got response: " + jsonFile1);
});
}).on('error', function(e) {
done(e);
console.log("Got error: " + e.message);
});
}
app.get('/', function(req, res) {
// Map the options through the getFile function, resulting in an array of each response
async.map(httpOptions, getFile, function (err, jsonFiles) {
// You should probably check for any errors here
res.render('home', {
data: jsonFiles
});
});
});