Receiving an empty request with Express server - javascript

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),
};

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);
}
}

HTTPS Node JS POST issue

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();

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

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}....`));

Http get multiple json files from different API endpoints using node express

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
});
});
});

Categories