Post Request stuck on Postman - node.js

I am learning to build API using Node.js, Express and MongoDB. I am on early learning phase.
My code are as follow.
const app = express();
const mongojs = require("mongojs");
const { body, param, validationResult } = require("express-validator");
const db = mongojs("travel", ["records"]);
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.get("/api/records", function (req, res) {
const options = req.query;
const sort = options.sort || {};
const filter = options.filter || {};
const limit = 2;
const page = parseInt(options.page) || 1;
const skip = (page - 1) * limit;
for (var i in sort) {
sort[i] = parseInt(sort[i]);
}
db.records
.find(filter)
.sort(sort)
.skip(skip)
.limit(limit, function (err, data) {
if (err) {
return res.sendStatus(500);
} else {
return res.status(200).json({
meta: {
filter,
sort,
skip,
limit,
page,
total: data.length,
},
data,
links: {
self: req.originalUrl,
},
});
}
});
});
app.post("/api/records", function (req, res) {
db.records.insert(req.body, function (err, data) {
if (err) {
return res.status(500);
}
const _id = data._id;
res.append("Location", "/api/records/" + _id);
return res.send(201).json({
meta: { _id },
data,
});
});
});
app.listen(8000, function () {
console.log("Server running at port 8000...");
});
When I try GET request on Postman, it works fine. But when I try POST request, it shows like the following. error msg image link.
Please let me know what is wrong here.
Thanks in advance

Related

postman not working while performing get and post method in nodejs

postman stuckplease check the code if any mistake i did because in postman while sending the post request ,im not getting any response , it is only showing sending request .
Mongodb also connected .
this is my index.js code , please help me out of this
process.env.TZ = 'Asia/Calcutta';
var port = process.env.PORT || 5000;
var cCPUs = require('os').cpus().length;
const cluster = require('cluster');
const express = require('express');
const reader = require('xlsx');
const path = require('path');
const app = express();
const multer = require('multer');
const mongoose = require('mongoose');
const db = require('./Config/Keys').mongoURI;
const logger = require('./Config/workerlog');
const myrecord = require('./model/myrecord');
mongoose
.connect(db, {
keepAlive: true,
})
.then(() => logger.info('MongoDB Connected'))
.catch((err) => console.log(err));
var storage = multer.diskStorage({
filename: function (req, file, cb) {
var datetimestamp = Date.now();
cb(
null,
file.fieldname +
'-' +
datetimestamp +
'.' +
file.originalname.split('.')[file.originalname.split('.').length - 1]
);
},
});
var uploads = multer({
storage: storage,
fileFilter: function (req, file, callback) {
//file filter
if (
['xls', 'xlsx', 'csv'].indexOf(
file.originalname.split('.')[file.originalname.split('.').length - 1]
) === -1
) {
return callback(new Error('Wrong extension type'));
}
callback(null, true);
},
}).single('file');
app.post('/Getexcelfile', async function (req, res) {
uploads(req, res, async function (err) {
if (err) {
return res.status(404).json({ Message: 'Something went to wrong...!' });
}
if (!req.file) {
return res.status(404).json({ Message: 'Please Choose file' });
}
try {
const file = reader.readFile(`${req.file.path}`);
var data = [];
try {
var sheets = file.SheetNames;
for (let i = 0; i < sheets.length; i++) {
const temp = reader.utils.sheet_to_json(
file.Sheets[file.SheetNames[i]]
);
temp.forEach((res) => {
data.push(res);
});
}
} catch (e) {}
await record.insertMany(req.body.BulkData).then((res) => {
res.json({
path: req.file.path,
test: data,
});
res.json(ress);
});
} catch (e) {}
});
});
app.get('/GetRecordDetails', async (req, res) => {
myrecord.find().then((ResponseData) => {
res.json(ResponseData);
});
});
if (cluster.isMaster) {
// Create a worker for each CPU
for (var i = 0; i < cCPUs; i++) {
cluster.fork();
}
} else {
app.listen(port, () => console.log(`Listening on port ${port}`));
}
want to perform get and post in postman . please check the code and help me to solve the problems

How to I dynamically insert key and value in JSON in the response of NodeJs API

This is the Input I am providing
{
"cities" : [
"kolkata",
"mumbai",
"chennai"
]
}
and this is the response I am receiving.
{
"weather": [
{
"chennai": "30C"
},
{
"mumbai": "27C"
},
{
"kolkata": "26C"
}
]
}
I want a response somewhat like
{
"weather" : {
"kolkata" : "26C",
"mumbai": "27C",
"chennai": "30C"
}
}
My code is as follows.
const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser');
const request = require('request');
const app = express();
const apiKey = 'c6068c4018def9330b01366aed03b08e';
app.use(express.static('public'));
app.use(bodyParser.json());
router.post('/getWeather', function (req, res) {
let cities = req.body.cities;
let weatherJson = [];
for(let i=0; i<cities.length; i++)
{
let city = cities[i];
let url = `http://api.weatherstack.com/current?access_key=${apiKey}&query=${city}`;
request(url, function (response, body) {
if (response) {
return res.json({ error: response });
}
let weather = JSON.parse(body.body);
if (weather.current == undefined) {
return res.json({ error: "somethin went wrong!" });
}
let weatherText = `${weather.current.temperature}C`;
weatherJson.push({ [city] : weatherText });
if(weatherJson.length == cities.length) {
console.log("here");
res.json({"weather": weatherJson});
}
});
}
});
app.use('/', router);
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
});
I have tried adding as hashmap, adding in array format then using stringify at the response point, but nothing seems to work. I just want to convert the format of the response to the desirable one with as minimalistic change in the code as possible. Please help.
You have a few issues, first off you're storing weatherJson (response) as an array when you say you want it to be a map.
here's how I would implement this:
router.post("/getWeather", async function (req, res) {
let cities = req.body.cities;
let weatherJson = {};
for (let i = 0; i < cities.length; i++) {
let city = cities[i];
let url = `http://api.weatherstack.com/current?access_key=${apiKey}&query=${city}`;
try {
const response = await fetch(url);
let weather = JSON.parse(response.body);
if (weather.current == undefined) {
return res.json({ error: "somethin went wrong!" });
}
let weatherText = `${weather.current.temperature}C`;
weatherJson[city] = weatherText;
} catch (err) {
return res.json({ error: err });
}
}
res.json({ weather: weatherJson });
});
You should use node-fetch instead of request which is obsolete. It does the same thing but much cleaner with promises instead of callbacks.
try creating an object instead of an array.
const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser');
const request = require('request');
const app = express();
const apiKey = 'c6068c4018def9330b01366aed03b08e';
app.use(express.static('public'));
app.use(bodyParser.json());
router.post('/getWeather', function (req, res) {
let cities = req.body.cities;
let weatherJson = {};
for(let i=0; i<cities.length; i++)
{
let city = cities[i];
let url = `http://api.weatherstack.com/current?access_key=${apiKey}&query=${city}`;
request(url, function (response, body) {
if (response) {
return res.json({ error: response });
}
let weather = JSON.parse(body.body);
if (weather.current == undefined) {
return res.json({ error: "somethin went wrong!" });
}
let weatherText = `${weather.current.temperature}C`;
weatherJson[city]=weatherText;
if(Object.keys(weatherJson).length == cities.length) {
console.log("here");
res.json({"weather": weatherJson});
}
});
}
});
app.use('/', router);
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
});

The endpoints that are created with node.jsdoes not work properly?

I have a 2 different endpoint in index.js file. The android app calls and retrieves data with these endpoints from local MongoDB database. The first endpoint "/AddArac" works fine in starting but if ı Call "/AddArac" after calling "/ListArac" it gives an error.
For example:
/AddArac - /ListArac => this order is ok for both.
/ListArac - /AddArac => this order is not ok for /AddArac.
var mongodb = require('mongodb');
var objectID = mongodb.ObjectID;
var express = require('express');
var bodyparser = require('body-parser');
var app = express();
app.use(bodyparser.json());
app.use(bodyparser.urlencoded({ extended: true }));
var mongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017'
app.post('/AddArac', (request, response, next) => {
mongoClient.connect(url, { useNewUrlParser: true }, function (err, client) {
var db = client.db('basaranSMSDev');
var data = request.body;
var name = data.name;
var plaka = data.plaka;
var tel = data.tel;
var json = { 'name': name, 'plaka': plaka, 'tel': tel };
db.collection('Araclar').find({ 'plaka': plaka }).count(function (error, number) {
if (number > 0) {
response.json('Araç daha önce kaydedilmiş.');
}
else {
db.collection('Araclar').insertOne(json, function (error, res) {
if (err) {
res.json('Araç kaydında hata oluştu tekrar deneyiniz.');
console.log('Arac eklenemedi', err);
}
else {
res.json('Araç eklendi');
console.log('Arac eklendi.');
}
});
}
client.close();
});
});
});
app.get('/ListArac', (req, res) => {
mongoClient.connect(url, { useNewUrlParser: true }, function (err, client) {
var db = client.db('basaranSMSDev');
var items = db.collection('Araclar').find().toArray();
items.then(function (result) {
console.log(result)
res.json(result)
})
console.log(items);
client.close();
});
})
The error:
C:\Users\Dilber\Basarannodejs\node_modules\mongodb\lib\utils.js:106
throw err;
^
TypeError: res.json is not a function
at C:\Users\Dilber\Basarannodejs\index.js:138:29
at executeCallback (C:\Users\Dilber\Basarannodejs\node_modules\mongodb\lib\operations\execute_operation.js:70:5)
at C:\Users\Dilber\Basarannodejs\node_modules\mongodb\lib\operations\insert_one.js:34:21
at handleCallback (C:\Users\Dilber\Basarannodejs\node_modules\mongodb\lib\utils.js:102:55)
at C:\Users\Dilber\Basarannodejs\node_modules\mongodb\lib\operations\common_functions.js:269:5
at C:\Users\Dilber\Basarannodejs\node_modules\mongodb\lib\core\connection\pool.js:405:18
at processTicksAndRejections (node:internal/process/task_queues:75:11)
in your code
app.post('/AddArac', (request, response, next) => {
you have used response as the response parameter.
but you used res in
if (err) {
res.json('Araç kaydında hata oluştu tekrar deneyiniz.');
res is not a function in
db.collection('Araclar').insertOne(json, function (error, res) {

Node.js endpoint is not working but another one is working

I have 2 endpoints in Node.js index.js file.
First one is working well and it turns 200 OK. But the second one is not working, it turns 404 Error. I could not find the reason.
First endpoint is /AddArac. It works well and adds data to MongoDB database
Second endpoint is /AddMesaj. It doesn't work. Both endpoints have the same logic.
My nodejs file is here:
`
var mongodb = require('mongodb');
var objectID = mongodb.ObjectID;
var express = require('express');
var bodyparser = require('body-parser');
var app = express();
app.use(bodyparser.json());
app.use(bodyparser.urlencoded({ extended: true }));
var mongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017'
mongoClient.connect(url, { useNewUrlParser: true }, function (err, client) {
if (err) {
console.log('Connection Fail', err);
}
else {
var db = client.db('basaranSMSDev');
//Add arac
app.post('/AddArac', (request, response, next) => {
var data = request.body;
var name = data.name;
var plaka = data.plaka;
var tel = data.tel;
var json = { 'name': name, 'plaka': plaka, 'tel': tel };
db.collection('Araclar').find({ 'plaka': plaka }).count(function (error, number) {
if (number > 0) {
response.json('Araç daha önce kaydedilmiş.');
}
else {
db.collection('Araclar').insertOne(json, function (error, res) {
if (err) {
response.json('Araç kaydında hata oluştu tekrar deneyiniz.');
console.log('Arac eklenemedi', err);
}
else {
response.json('Araç eklendi');
console.log('Arac eklendi.');
}
});
}
});
});
//Araç listesi getirme
//add mesaj
app.post('AddMesaj', (request, response, next) => {
var data_mes = request.body;
var plaka = data_mes.plaka;
var mtext = data_mes.text;
var driver = data_mes.driver;
var date = data_mes.tarih;
var json = { 'plaka': plaka, 'text': mtext, 'driver': driver, 'date': date };
db.collection('Mesajlar').insertOne(json, function (error, res) {
if (err) {
response.json('Mesaj gönderiminde hata oluştu tekrar deneyiniz.');
console.log('Mesaj eklenemedi', err);
}
else {
response.json('Mesaj gönderildi');
console.log('Mesaj eklendi.');
}
});
});
app.listen(3000, () => {
console.log('Connection ok');
});
//Mesaj listesi getirme
}
}
);
`
Change to:
app.post('/AddMesaj', (request, response, next) => {

asynchronous code not working with event listener

*Edited for clarity and to reflect changes:
Hello. I'm struggling to understand why my async functions are working just fine individually, and when chained together, but not when chained together and fired off in an event listener....
worth noting: when i try to run this without an even listener, data passes from my app, through my post route, and to my endpoint the way it should, it is then returned to my app through the correct route, etc. However, i do get an error in the console that says :
error SyntaxError: Unexpected token < in JSON at position 0
however, when i try to run my chain of async functions on the click of a dom element i don't get the above error, data is passed to my post route, i can log the object that is posted:
Object: null prototype] { zipcode: '97206', feel: 'confused' }
but then my server doesn't save any data, and my get route is never triggered, and nothing gets sent back to my app.......
i'm fairly lost.....
full server and app code below:
server:
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cors());
app.use(express.static('public'));
//test values
let projectData = {
date: "today",
temp: "38",
feelings: "confused"
};
app.get("/", (req, res) => {
});
app.post("/postData", (req, res) => {
console.log(req.body)
projectData = {
date: req.body.date,
temp: req.body.temp,
feelings: req.body.feelings
}
console.log("post route was hit, saved:", projectData);
res.redirect("/")
});
app.get("/getData", (req, res) => {
console.log("getData route was hit, sent: ", projectData)
res.send(projectData);
})
app.listen(3000, (req, res) => {
console.log("Listening on port 3000");
});
app
let newDate = getDate();
const apiKey = "5fd7b3a253e67a551e88ff34a92b9e02";
const baseURL = "http://api.openweathermap.org/data/2.5/weather?";
// zip=${}&APPID=${}&units=metric;
const userData = {};
// returns the date //
function getDate() {
let d = new Date();
let newDate = d.getMonth() + "." + d.getDate() + "." + d.getFullYear();
return newDate;
}
//constructs string for api call, adds temp to userData object
const getData = async (apiUrl, zip, key) => {
const url = `${apiUrl}zip=${zip}&APPID=${key}&units=metric`;
const result = await fetch(url);
try {
let newData = await result.json()
// console.log(newData.main.temp)
userData.temp = newData.main.temp
}catch(error) {
console.log("error", error);
}
}
// getData(baseURL, 97206, apiKey)
// .then(result => {
// console.log(userData)
// })
//saves contents of userData Object to server
const postData = async (url, data) => {
const result = await fetch(url, {
method: "POST",
credentials: "same-origin",
headers: {
"Content-type": "application/json"
},
body: JSON.stringify(data)
});
try {
const newData = await result.json();
// console.log(newData);
return newData;
} catch (error) {
console.log("error", error);
}
};
// postData('/postData', userData);
//updates interface with projectData values from server
const updateUI = async url => {
const result = await fetch(url);
try {
const newData = await result.json();
document.getElementById("date").innerHTML = newData.date;
document.getElementById("temp").innerHTML = newData.temp;
document.getElementById("feelings").innerHTML = newData.feelings;
} catch (error) {
console.log("error", error);
}
};
// updateUI("/getData")
// THIS WORKS
userData.date = newDate;
userData.feelings = document.getElementById("feel").value;
const zipCode = document.getElementById("zipcode").value;
getData(baseURL, 97206, apiKey).then(result => {
postData("/postData", userData).then(result => {
updateUI("/getData");
});
});
// THIS DOESNT WORK
// document.getElementById("btn").addEventListener("click", e => {
// userData.date = newDate;
// userData.feelings = document.getElementById("feel").value;
// const zipCode = document.getElementById("zipcode").value;
// getData(baseURL, zipCode, apiKey).then(result => {
// postData("/postData", userData).then(result => {
// updateUI("/getData");
// });
// });
// });
EDIT:
I realized that the information that was being passed through the post route when my async functions are fired off by an event listener was actually just the form input element values, rather than the contents of the fetch/post request. after i removed the name attributes from the form inputs, i'm getting no data at all hitting my post route......yet the corosponding function works fine with not in the event listener.
I'm stumped.
well, the syntax error was solved by using .text() instead of .json() on the results of my post request.
adding e.preventDefault() as the first line of my event listener callback fixed the event listener, and now everything is working as it should.

Resources