How to send a POST request from node.js Express? - javascript

Could someone show me the simplest way to send a post request from node.js Express, including how to pass and retrieve some data? I am expecting something similar to cURL in PHP.

var request = require('request');
function updateClient(postData){
var clientServerOptions = {
uri: 'http://'+clientHost+''+clientContext,
body: JSON.stringify(postData),
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
}
request(clientServerOptions, function (error, response) {
console.log(error,response.body);
return;
});
}
For this to work, your server must be something like:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json())
var port = 9000;
app.post('/sample/put/data', function(req, res) {
console.log('receiving data ...');
console.log('body is ',req.body);
res.send(req.body);
});
// start the server
app.listen(port);
console.log('Server started! At http://localhost:' + port);

As described here for a post request :
var http = require('http');
var options = {
host: 'www.host.com',
path: '/',
port: '80',
method: 'POST'
};
callback = function(response) {
var str = ''
response.on('data', function (chunk) {
str += chunk;
});
response.on('end', function () {
console.log(str);
});
}
var req = http.request(options, callback);
//This is the data we are posting, it needs to be a string or a buffer
req.write("data");
req.end();

you can try like this:
var request = require('request');
request.post({ headers: {'content-type' : 'application/json'}
, url: <your URL>, body: <req_body in json> }
, function(error, response, body){
console.log(body);
});

in your server side the code looks like:
var request = require('request');
app.post('/add', function(req, res){
console.log(req.body);
request.post(
{
url:'http://localhost:6001/add',
json: {
unit_name:req.body.unit_name,
unit_price:req.body.unit_price
},
headers: {
'Content-Type': 'application/json'
}
},
function(error, response, body){
// console.log(error);
// console.log(response);
console.log(body);
res.send(body);
});
// res.send("body");
});
in receiving end server code looks like:
app.post('/add', function(req, res){
console.log('received request')
console.log(req.body);
let adunit = new AdUnit(req.body);
adunit.save()
.then(game => {
res.status(200).json({'adUnit':'AdUnit is added successfully'})
})
.catch(err => {
res.status(400).send('unable to save to database');
})
});
Schema is just two properties unit_name and unit_price.

I use superagent, which is simliar to jQuery.
Here is the docs
And the demo like:
var sa = require('superagent');
sa.post('url')
.send({key: value})
.end(function(err, res) {
//TODO
});

Try this. It works for me.
const express = require("express");
const app = express();
app.use(express.json());
const PORT = 3000;
const jobTypes = [
{ id: 1, type: "Interior" },
{ id: 2, type: "Etterior" },
{ id: 3, type: "Roof" },
{ id: 4, type: "Renovations" },
{ id: 5, type: "Roof" },
];
app.post("/api/jobtypes", (req, res) => {
const jobtype = { id: jobTypes.length + 1, type: req.body.type };
jobTypes.push(jobtype);
res.send(jobtype);
});
app.listen(PORT, console.log(`Listening on port ${PORT}....`));

Related

Express fetching data promise is pending

I've written 2 snippets of code - client and server. When the client clicks the button he sends information to the server, which uses the Riot API to retrieve summoner info. Now I want to send it back to the client but once I fetch it my promise response is pending and result is undefined. Promises are a new thing for me. Here's the code,
Client:
<!DOCTYPE html>
<html>
<head>
<script>
function sendInfo(){
let name = document.getElementById("checker").value;
let data = {name};
fetch("/api", {
method: "POST",
headers: {
"Content-type": "application/json"
},
body: JSON.stringify(data)
});
//let data = document.getElementById("levelID");
fetch("/level", {
headers : {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.then(function(res){
console.log(res.json());
})
.then(function(data){
console.log(data);
})
.catch(function(error){
console.log(error);
});
}
</script>
</head>
<body>
<input type="text" name="checkPlayer" id="checker"><br>
<button onclick="sendInfo()">Search summoner!</button>
</body>
</html>
Server:
const PORT = 3000;
const axios = require("axios");
const express = require("express");
const path = require('path');
const key = "RGAPI-50e38ac8-4629-4abc-aef9-68e4259448bd";
const parser = require("body-parser");
var jsonParser = parser.json();
//let puuid, summonerID, level;
let summoner;
const app = express();
app.listen(PORT, () => {
console.log("listening at 3000");
});
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, '/main.html'));
//searchBySummonerName("RnkzOnFire");
});
app.post("/api", jsonParser, (req, res) => {
searchBySummonerName(req.body.name);
});
app.get("/level", (req, res) => {
res.writeHead(200, {"Content-Type": "application/json"});
res.write(JSON.stringify(summoner));
});
function searchBySummonerName(name){
const searchURL = "https://eun1.api.riotgames.com/lol/summoner/v4/summoners/by-name/" + name + "?" + "api_key=" + key;
axios.get(searchURL).then((res) => {
summoner = res.data;
});
}

I'm getting empty request body in express.js

I'm trying to get my data in my database but not getting anything in the body of the request. I have used parse-body and CORS but it still not working.
I tried several things but did not work.
Backend code:
const bodyParser = require('body-parser');
const cors = require('cors');
const port = 5000;
const app = express();
app.use(cors());
app.use(bodyParser.json());
const MongoClient = require("mongodb").MongoClient;
const uri = "mongodb+srv://ishadDB#cluster0.gi4fd.mongodb.net/?retryWrites=true&w=majority";
const client = new MongoClient(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
client.connect((err) => {
const bookings = client.db("BurjAlArab").collection("bookings");
console.log("Connected");
app.post('/addBooking', (req, res) => {
console.log(req)
const newBooking = req.body;
console.log(newBooking);
bookings.insertOne(newBooking)
.then(res => {
res.send(result.insertedCount > 0);
});
});
});
app.get("/", (req, res) => {
res.send("Hello World!");
});
app.listen(port);
front end:
const handleBooking = () => {
const newBooking = { ...loggedInUser, ...selectedDate };
fetch('http://localhost:5000/addBooking', {
method: 'POST',
header: { 'Content-Type' : 'application/json' },
body : JSON.stringify({newBooking})
})
.then((res) => res.json())
.then((data) => {
console.log(data);
});
};
Can anyone help me out?
Try to send it in your frontend with the following code
This take use of await
Notice because of the use of await the function have to be async
async function bla(){}
async function bla(){
const data = {newBooking};
const options = {
method: 'POST',
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data)
};
await fetch('/addBooking', options);
}
}

Sending data with vanilla JS ajax and reading it with Node api

I have this code on my client side:
sendMail(e) {
e.preventDefault();
var name = document.getElementById('name').value;
var contactReason = document.getElementById('contactReason').value;
var email = document.getElementById('email').value;
var additionalInfo = document.getElementById('additionalInfo').value;
var body = {
name: name,
contactReason: contactReason,
email: email,
additionalInfo: additionalInfo,
};
console.log(body);
fetch('http://localhost:4000/', {
method: 'POST',
body: body.toString(),
}).then(r => console.log(r)).catch(e => console.log(e));
}
And this kind of works. It logs the object to the console, and sends something to the back end.
Here's my Node call:
var express = require('express');
var router = express.Router();
var cors = require('cors');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({extended: true}));
app.use(cors());
app.options('*', cors());
var a = '=';
router.post('/', (req, res, next) => {
console.log('mailing');
console.log(a);
console.log(req.body);
a += '=';
var nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport({
host: "smtp.gmail.com", // hostname
auth: {
user: '******',
pass: '******'
}
});
let mailOptions = {
from: `${req.body.name} ${req.body.email}`, // sender address
to: 'alexander.ironside#mygeorgian.ca', // list of receivers
subject: 'Email from UczSieApp contact form', // Subject line
text: 'Hello world ', // plaintext body
html: `
<h4>Imie: ${req.body.name}</h4>
<h4>Email: ${req.body.email}</h4>
<h4>Powod kontaktu: ${req.body.contactReason}</h4>
<p>Wiadomosc: ${req.body.additionalInfo}</p>
`
};
// send mail with defined transport object
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
return console.log(error);
}
console.log('Message sent: ' + info.response);
});
}
);
module.exports = router;
So what the code does right now:
The object is being created, something (not sure what exactly) is being send to Node back-end, and an email is being sent. But req.body is logged as {}.
What I want to do:
Read the values sent to the back-end as body and send an email with this data.
What am I missing?
I used GET instead of POST and this solved my problems. It is kind of a cheat but it works.
should add to fetch
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(body),
all correct code
frontend
sendMail(e) {
e.preventDefault();
var name = document.getElementById('name').value;
var contactReason = document.getElementById('contactReason').value;
var email = document.getElementById('email').value;
var additionalInfo = document.getElementById('additionalInfo').value;
var body = {
name: name,
contactReason: contactReason,
email: email,
additionalInfo: additionalInfo,
};
console.log(body);
fetch('http://localhost:4000/', {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(body),
method: 'POST',
}).then(r => console.log(r)).catch(e => console.log(e));
}
backend
var express = require('express');
var router = express.Router();
var cors = require('cors');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({extended: true}));
app.use(cors());
app.options('*', cors());
var a = '=';
router.post('/', (req, res, next) => {
console.log('mailing');
console.log(a);
console.log(req.body);
a += '=';
var nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport({
host: "smtp.gmail.com", // hostname
auth: {
user: '******',
pass: '******'
}
});
let mailOptions = {
from: `${req.body.name} ${req.body.email}`, // sender address
to: 'alexander.ironside#mygeorgian.ca', // list of receivers
subject: 'Email from UczSieApp contact form', // Subject line
text: 'Hello world ', // plaintext body
html: `
<h4>Imie: ${req.body.name}</h4>
<h4>Email: ${req.body.email}</h4>
<h4>Powod kontaktu: ${req.body.contactReason}</h4>
<p>Wiadomosc: ${req.body.additionalInfo}</p>
`
};
// send mail with defined transport object
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
return console.log(error);
}
console.log('Message sent: ' + info.response);
});
}
);
module.exports = router;

Authentication with NodeJS, Express-Session and Passport fails

I am successfully authenticating and logging in with the google OAuth API.
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
const passportInit = require('./app/routes/auth')
const session = require('express-session');
module.exports = (app, db, passport) => {
app.use(session({secret: "ahskfjdhkjshadkjfhlajsdhlfkj"}));
passportInit(passport)
app.use(passport.initialize());
app.use(passport.session())
app.get('/', (req, res) => {
if (req.session.token) {
res.cookie('token', req.session.token);
res.json({
status: 'session cookie set'
});
console.log(req.session.token);
console.log(JSON.stringify(req.user))
} else {
res.cookie('token', '')
res.json({
status: 'session cookie not set'
});
}
});
app.get('/auth/google', passport.authenticate('google', {
scope: ['https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/youtube']
}));
app.get('/auth/google/callback',
passport.authenticate('google', {
failureRedirect: '/' // Fail: To err Page
}),
(req, res) => {
req.session.token = req.user.token;
userString = JSON.stringify(req.user);
userObjectValue = JSON.parse(userString);
userId = userObjectValue['profile'].id;
userName = userObjectValue['profile'].name;
userGivenName = userName.givenName;
const details = {'userId': userId};
db.collection('users').findOne(details, (err, item) => {
if (item == null) {
res.redirect('http://localhost:80/Register.html');
} else {
if(item['rolle'] == 'yt') {
res.redirect('http://localhost:80/YT_Welcome.html');
} else {
res.redirect('http://localhost:80/WT_Welcome.html');
}
}
});
}
);
app.get('/logout', (req, res) => {
req.logout();
req.session.token = null;
res.redirect('/');
});
}
Now I want to make a POST request from my frontend to my NodeJS backend.
Frontend-Request:
function registerWT() {
console.log('registerWT started...')
var rolle = 'wt';
var json = {"rolle": rolle};
$.ajax({
url: 'http://localhost:8000/user',
type: 'POST',
data: JSON.stringify(json),
contentType: 'application/json; charset=utf-8',
dataType: 'JSON',
async: false,
success: function (msg) {
var js = JSON.stringify(msg);
var state = msg['state'];
if (state == true) {
console.log('successfully created new user')
} else {
console.log('failed to create new user')
}
}
});
Backend-API:
var ObjectID = require('mongodb').ObjectID;
const passport = require('passport');
const passportInit = require('./auth');
module.exports = (app, db) => {
app.post('/user', (req, res) => {
console.log("POST USER REACHED!"); // This is printed out...
console.log(req.body.rolle); //is printed out correctly
console.log(req.user); // Is undefined...
if (!req.isAuthenticated()) { return res.send({'error':'unauthorized'}) } //Authentication fails...
console.log(req.user.userId);
console.log(req.userGivenName);
console.log(req.body.rolle);
userId = req.user.userId;
userGivenName = req.user.userGivenName;
userRolle= req.body.rolle;
const details = { userId: userId, userGivenName: userGivenName, rolle: userRolle };
db.collection('users').insert(details, (err, result) => {
if (err) {
res.send({ 'error': 'An error has occurred' });
} else {
res.send(result.ops[0]);
}
});
});
}
From my understanding the user authentication data should be send automaticly with every request I am doing from my frontend to my backend, since I logged in via google before. Is this correct or do I miss to include something in my frontend JS request code?
What is interessting is that after I logged in, I have to trouble with navigating to /user. So there is no problem with manualy doing a get request to this API, where I am also checking for authentication.
app.get('/user', (req, res) => {
if (!req.isAuthenticated()) { return res.send({'error':'unauthorized'}) }
db.collection('users').find({}).toArray((err, item) => {
if (err) {
res.send({'error':'An error has occurred'});
} else {
res.json(item)
}
});
});
But when I am making a Get request with JavaScript, the authentication fails again...
JavaScript get request:
function getTest() {
console.log('YT');
$.ajax({
url: 'http://localhost:8000/user',
type: 'GET',
async: false,
success: function (msg) {
var state = msg['state']; //nehmen den Wert von state aus der JSON
if (state == true) {
console.log('successfully created new user')
} else {
console.log('failed to create new user')
}
}
});
}
Does someone know what I am doing wrong here?
Edit:
My passportInit:
const GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
const keys = require('../../config/keys')
module.exports = (passport) => {
passport.serializeUser((user, done) => {
done(null, user);
});
passport.deserializeUser((user, done) => {
done(null, user);
});
passport.use(new GoogleStrategy({
clientID: keys.google.clientID,
clientSecret: keys.google.cientSecret,
callbackURL: keys.google.callback
},
(token, refreshToken, profile, done) => {
return done(null, {
profile: profile,
token: token
});
}));
};
Edit2: Added cors package:
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');
const db = require('./config/db');
const keys = require('./config/keys')
const passport = require('passport');
const express = require('express');
const app = express();
const GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
const cors = require('cors')
const port = 8000;
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors({ origin: 'http://localhost' })); //configuring cors
MongoClient.connect(db.url, (err, database) => {
if (err) return console.log(err)
app.options('*', cors()) // enable pre-flight across-the-board
require('./authenticate')(app, database,passport);
require('./app/routes')(app, database, passport);
app.listen(port, () => {
console.log('We are live on ' + port);
});
});
I finally was able to solve the problem.
No, Browser Plug-in or something like this is needed!
Please see my Code below.
Frontend-Request:
function register() {
var role = 'wt';
var json = {"role": role};
$.ajax({
url: 'http://localhost:8000/user',
type: 'POST',
data: JSON.stringify(json),
contentType: 'application/json; charset=utf-8',
dataType: 'JSON',
xhrFields: {
withCredentials: true
},
crossDomain: true,
async: false,
success: function (msg) {
var state = msg['state'];
if (state == true) {
console.log('successfully created new WT')
location.href = 'http://localhost:80/WT_Welcome.html'
} else {
console.log('failed to create new WT')
location.href = 'http://localhost:80/index.html'
}
}
});
}
Backend Server.js
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');
const db = require('./config/db');
const keys = require('./config/keys')
const passport = require('passport');
const express = require('express');
const app = express();
const GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
const port = 8000;
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
MongoClient.connect(db.url, (err, database) => {
if (err) return console.log(err)
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', "http://localhost");
res.header('Access-Control-Allow-Methods','GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Credentials', true)
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
})
require('./authenticate')(app, database,passport);
require('./app/routes')(app, database, passport);
app.listen(port, () => {
console.log('We are live on ' + port);
});
});
Backend API:
app.post('/user', (req, res) => {
if (!req.isAuthenticated()) { return res.send({'error':'unauthorized'}) } //Authentication fails...
userString = JSON.stringify(req.user);
userObject = JSON.parse(userString)
userId = userObjectValue['profile'].id;
userName = userObjectValue['profile'].name; //not used
userGivenName = userName.givenName;
userRolle= req.body.rolle;
const details = { userId: userId, userGivenName: userGivenName, rolle: userRolle };
console.log(details);
db.collection('users').insert(details, (err, result) => {
if (err) {
res.send({ 'state': false });
} else {
res.send({'state' : true});
}
});
});

How do I make a post request with a JSON payload to an external API using node?

I am trying to make a POST request with a JSON payload to an external API using node.
Here is my code:
var express = require('express');
var bodyParser = require('body-parser');
var cors = require('cors');
var url = require("url");
var http = require("http");
var app = express();
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.post('/api', function(req, res) {
var query = url.parse(req.url, true).query;
var key = query.key;
console.log('JSON PAYLOAD:');
console.log(req.body); **//PAYLOAD COMES THROUGH AS EXPECTED**
var options = {};
options = {
host: 'localhost',
port: 1234,
method: 'POST',
headers: {'Content-Type': 'application/json'},
path: '/api?key=1234'
};
var request = http.request(options, function(response) {
response.setEncoding('utf-8');
var responseString = '';
response.on('data', function(data) {
responseString += data;
});
response.on('end', function() {
var resultObject = JSON.parse(responseString);
res.json(resultObject);
});
});
request.on('error', function(e) {
});
request.write(req.body) **//THIS METHOD SHOULD BE FORWARDING THE PAYLOAD BUT THIS IS NOT THE CASE...**
request.end();
});
The JSON payload comes through as expected from the origin. However I am unable to forward this payload to the external API. 'request.write(req.body)' appears to be the way to do this, however the external API is still receiving a null payload.
Any help would be appreciated. Thanks.
Try this Inside the app.post block
var options = {
host: 'localhost',
path: '/api?key=1234',
port: 1234,
method: 'POST',
headers: {'Content-Type': 'application/json'}
};
callback = function(response) {
var str = ''
response.on('data', function (chunk) {
str += chunk;
});
response.on('end', function () {
console.log(str);
});
}
var req = http.request(options, callback);
req.write(JSON.stringify(req.body));
req.end();

Categories