I'm making an http post request to my express web server sending dummy data as json. It correctly receives the request and can send back a json object, but for some reason it can't manage to access the post request body.
I'm using this code for express:
const express = require('express');
const app = express();
const port = 3000;
app.post('/test', (req, res) => {
console.log(req.body);
res.json({"some": "thing"});
});
app.listen(port, () => {
console.log(`Listening at http://localhost:${port}`)
});
And this is the code of the request:
const req = http.request({
hostname: '127.0.0.1',
port: 3000,
path: '/test',
method: 'POST',
json: {
url: "https://www.nothing.com",
name: "hello"
}
}, res => {
console.log(`statusCode: ${res.statusCode}`)
res.on('data', d => {
process.stdout.write(d)
})
})
req.on('error', error => {
console.error(error)
})
req.end()
As you can see I'm running this locally. The client receives a status code 200 and the json {"some": "thing"} sent by the server, but the server gets "undefined" from req.body. I tried using:
headers: {
'Content-Type': 'application/json'
}
body: JSON.stringify({
url: "https://www.nothing.com",
name: "hello"
})
instead of json directly in the request options, but to no avail. I even tried using app.use(express.json()); as someone suggested.
What is the problem?
Apparently the way I was doing the post request was not correct, I had to send the body in a separate line with req.write(), like this:
const http = require('http');
const data = JSON.stringify({ //<--- data to send as body
url: "https://www.nothing.com",
name: "hello"
});
const req = http.request({
hostname: '127.0.0.1',
port: 3000,
path: '/test',
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
}, res => {
console.log(`statusCode: ${res.statusCode}`);
res.on('data', d => {
process.stdout.write(d);
})
})
req.on('error', error => {
console.error(error);
})
req.write(data); //<--- this line
req.end();
You have to add body-parser middleware http://expressjs.com/en/resources/middleware/body-parser.html
req.body empty on posts
Related
I have an application wherein after getting the data from user, I am posting it to the /create
route.
However upon making a post request, it gives me error:
POST http://localhost:5000/create 404 (Not Found)
The code for making post request:
submitbtn.addEventListener('click', (e) => {
e.preventDefault();
const data=validateForm();
if (data) {
postData(data);
console.log("submitted");
}
})
async function postData(data) {
await fetch('http://localhost:5000/create', {
method: 'POST',
body: {
title: `${data.title}`, content: `${data.text}`
},
headers: {
'Content-Type': 'application/json'
}
})
}
Handling the post request on my server:
const express=require('express');
const app= express();
const router=express.Router();
const News=require('./news/news');
app.use(express.static('./public'));
router.post('/create',(req,res)=>{
res.send("Successful");
})
app.listen(5000,()=>{
console.log("Server listening on 5000 port");
})
I have been dealing with this issue where I am attempting to make a get request to a third-party API using Axios in my Node.js server. The endpoint requires a username and password which I am passing along as follows:
export const getStream = async(req, res) => {
let conn = createConnection(config);
let query = `SELECT * FROM cameras WHERE id = ${req.params.id}`
conn.connect();
conn.query(query, async (error, rows, _) => {
const camera = rows[0];
const {ip, user, pass} = camera;
if (error) {
return res.json({ "status": "failure", "error": error });
}
const tok = `${user}:${pass}`;
const userPass = Buffer.from(tok)
const base64data = userPass.toString('base64');
const basic = `Basic ${base64data}`;
const result = await axios({
method: 'get',
url: `<API URL>`,
headers: {
'Authorization': basic,
'Content-Type': 'multipart/x-mixed-replace; boundary=--myboundary'
},
auth: {username: user, password: pass}
})
res.json(result)
});
conn.end();
}
I am then calling this endpoint in my React front-end as such:
const getStream = async () => {
try {
const result = await publicRequest.get(`camera/getStream/${id}`)
console.log(result)
} catch (error) {
console.error(error)
}
}
Each time I make this request, my node server crashes and I get a 401 unauthorized error in my console. It appears that my Authorization header is not getting passed to the server even though everything else gets passed along as so.
headers: {
Accept: 'application/json, text/plain, */*',
'Content-Type': 'multipart/x-mixed-replace; boundary=--myboundary',
'User-Agent': 'axios/0.26.1'
},
method: 'get',
url: '<url>',
auth: { username: '<username>', password: '<password>' },
data: undefined
For extra information, this is how my node server is setup
import express, { urlencoded, json } from 'express';
import userRoute from './routes/userRoute.js';
import cameraRoute from './routes/cameraRoute.js';
import cors from 'cors';
const app = express();
app.use(cors());
app.options('*', cors());
app.use(json())
app.use(urlencoded({ extended: true }));
app.use(express.static('public'));
app.use('/api/user', userRoute);
app.use('/api/camera', cameraRoute);
const port = process.env.PORT || 8080;
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
I have been working on this issue for several days and each time I try something new, I always get a 401 error, and the server crashes.
Any suggestions would be greatly appreciated.
I am getting Status 400 error with below Nodejs code
This is trying to send https post request to abc.xyz on port 12345
I am unable to figure what is wrong here.
Although I am not Nodejs expert
const https = require('https');
const options = {
hostname: 'abc.xyz',
port: 12345,
path: '/test/',
method: 'POST',
json: true,
rejectUnauthorized: false
};
exports.handler = (event, context, callback) => {
const req = https.request(options, (res) => {
let body = '';
console.log('Status:', res.statusCode);
console.log('Headers:', JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', (chunk) => body += chunk);
res.on('end', () => {
console.log('Successfully processed HTTPS response');
// If we know it's JSON, parse it
if (res.headers['content-type'] === 'application/json') {
body = JSON.parse(body);
// console.log('Body: ' + body);
}
callback(null, body);
});
});
req.on('error', callback);
// req.write(JSON.stringify(event.data));
//console.log(event.data);
req.end();
};
You can only host these applications on localhost when testing.
You also need an app.listen(LOCALHOST:PORT);
A simple Nodejs tutorial will give you a deeper explanation.
This is a simple node server running on localhost 8080, no one else can see it.
var http = require('http');
//create a server object:
http.createServer(function (req, res) {
res.write('Hello World!'); //write a response to the client
res.end(); //end the response
}).listen(8080); //the server object listens on port 8080
I'm having an issue with the following code. I'm trying to make a POST request (json) to a URL using pipe but I get the error "write after end" - Internal Server Error. Can someone please help?
test: function( req, res, next) {
var requesty = request.post({
url: dataUrl,
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(body)
});
req.pipe(requesty).on('error', function (error) {
logger.withRequestLog(res, 'error', 'CC Melville Proxy failed!', {
assetUrl: dataUrl,
error: error,
});
next(error);
}).pipe(res);
}
You are getting error because of body: JSON.stringify(body). You can't (also don't need) to pass body as when you are piping raw bytes are being piped as well. Also This middleware should be FIRST as you don't want to use bodyParser etc which will read the stream and make it empty.
Below is an working example where I am proxying my request to one my routes(It can be external also):
const express = require('express');
const app = express();
const request = require('request');
const bodyParser = require('body-parser').json();
const dataUrl = '/employees'
app.use(dataUrl, bodyParser, (req, res)=>{
res.json({
body: req.body || {},
method: req.method,
param: req.params,
headers: req.headers,
url: req.url
});
})
app.use('/', (req, res) => {
var requesty = request({
url: 'http://localhost:8080'+dataUrl,
headers: {
'Content-Type': 'application/json'
},
})
req.pipe(requesty).on('error', function (error) {
console.log('error', 'CC Melville Proxy failed!', {
assetUrl: dataUrl,
error: error,
});
}).pipe(res);
});
app.listen(8080, () => {
console.log('started');
})
Note: You don't need to specify method as it will automatically be passed. From the doc:
You can also pipe() from http.ServerRequest instances, as well as to
http.ServerResponse instances. The HTTP method, headers, and
entity-body data will be sent.
I'm trying to get an access token via a POST request from the Twitch API but my http.request is never executing (I don't think) and I can't figure out why.
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var fs = require('fs');
var https = require('https');
var querystring = require('querystring');
var authInfo = require('./authInfo.json');
app.get('/twitch/auth', function(req, res) {
res.send("auth page");
var data = querystring.stringify({
client_id: authInfo.clientID,
client_secret: authInfo.clientSecret,
grant_type: "authorization_code",
redirect_uri: authInfo.redirectURI,
code: req.query.code,
state: 12345
});
var options = {
host: 'api.twitch.tv',
port: 443,
path: '/kraken/oauth2/token',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(data)
}
}
var req = https.request(options, (res) => {
console.log('statusCode:', res.statusCode);
console.log('headers:', res.headers);
res.on('data', (d) => {
console.log(d);
});
});
req.on('error', (e) => {
console.log(e);
});
req.end();
});
app.listen(port, function() {
console.log('Point browser to: http://localhost:' + port);
});
PS I've omitted the some code for brevity but I get back an authorization code successfully.
I solved my problem. I wasn't writing data to the body.
...
req.write(data);
req.end();
});
...