POST request with the Request modul in node not working - javascript

I'm trying to send a POST request to my API using the request module but i get nothing back and when i console log the request data i see the fields are undefined as shown in the image below. Dont know why.
I've tried to solve the issue but no success. I don't know what is wrong. But when i try to send data to the same API via POSTMAN it works fine as seen in the image below. So i dont know why its not working when i send data from the front end of my app
i need help in figurig this out.
Heres's my server side code
let express = require('express'),
bodyParser = require('body-parser'),
request = require('request'),
//connect = require('connect'),
jobRoutes = require('./routes/jobs'), //ddd
// db = require('./models/app'), //ddd
// helpers = require('./helpers/jobs'),
// fetch = require("node-fetch"),
path = require('path'),
router = express.Router(),
app = express(),
port = process.env.PORT || 3000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static('public'));
app.use(express.static(path.join(__dirname + '/public')));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use('/api/jobs', jobRoutes);
app.post('/jobs', (req, res)=>{
let formBody = {
title: req.title,
category: req.body.category,
description: req.body.description,
type: req.body.type,
url: req.body.url,
email: req.body.email,
apply: req.body.apply,
location: req.body.location,
company: req.body.company,
createdAt: Date.now()
};
request.post(console.log(formBody),{url:'http://localhost:3000/api/jobs/', form: formBody
}, function optionalCallback(err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}else{
console.log('Upload successful! Server responded with:', body);
}
return res.redirect('/jobs')
});
})
app.listen(port, process.env.PORT, process.env.IP, ()=> console.log(`Server is running on ${port}`))
And here's what the receiving end server code looks like
let db = require ('../models/app');
exports.createJob = (req, res) => {
console.log('The req body:',req.body)
db.Job.create(req.body)
.then((newJob) => {
res.status(201).json(newJob)
})
.catch((err) => {
res.send(err)
})
}
You can checkout the current repo for more clarity

But when i try to send data to the same API via POSTMAN it works fine as seen in the image below.
The image shows that the Content-Type of the request from Postman will be application/json but the code using the request module is going to send one with a Content-Type of application/x-www-form-urlencoded.
Presumably (your "receiving end server code" does not show the bodyParser), your server only supports JSON formatted requests.
Either configure the server to support application/x-www-form-urlencoded or make the request send JSON.

Related

How to get file data and other form data sent in POST request in Node Js

I am sending form data values using Postman as given here. Postman Request.
I am making use of NodeJS server in the backend to get the data from this POST request.
The code for my app.js file is given below.
require('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const port = process.env.PORT || 8080;
const app = express();
app.use(bodyParser.json({
limit: '50mb',
}));
app.use(bodyParser.urlencoded({
limit: '50mb',
extended: true
}));
const { multerUploadOneFile } = require(path.resolve(__dirname, 'helpers', 'multerConfig'));
app.post('/upload', function (req, res) {
// **Here I need to get the other parameters in the request body, i.e ```userId```, ```fileType```
console.log(req.body);
multerUploadOneFile(req, res, function (error) {
if (error) {
return res.status(401).send({
status: 'failure',
message: error.message
});
}
return res.status(200).send({
status: 'success',
message: 'successfully uploaded file.',
});
})
});
I am logging the request body in /upload api endpoint but I am not able to get anything. Please let me know how can I get the req.body in callback of /upload api endpoint.
body-parser doesn't support multi-part bodies.
multer (which you're correctly using) does, however it needs to execute and parse the request before you'll be able to access anything.
multerUploadOneFile needs to execute before you have acceess to .body or .file.
app.post('/upload', function (req, res) {
multerUploadOneFile(req, res, function (error) {
console.log(req.body, req.file);

Cant render EJS file as a Response to POST request

I've just started learning Express and Servers.
Problem
Just wanted to load another EJS page onto my localhost:4000/ path as a response after a POST request has been made for a form.
However, although I do get the response of the EJS page with the data from the req.body in the form from the client-side. I can't seem to get the page to load on the browser.
Any ideas? pls help
Express.js Server
let express = require('express');
let app = express();
let bodyParser = require('body-parser');
let path = require('path');
let fs = require('fs');
var urlencodedParser = bodyParser.urlencoded({extended:true});
app.use(express.json());
app.set('view engine', 'ejs');
app.use('/', express.static(__dirname + '/views'));
app.use('/', express.static(__dirname + '/views/partial'));
//Handling the GET request with the render of EJS file "index"
app.get('/', (req, res)=> {
res.render('index');
});
//Handling the POST request from the client, and sending the EJS file "createAccount" as a response
app.post('/', urlencodedParser, (req, res) => {
res.set('cache-control', 'max-age=0; private; no-cache');
res.render('createAccount', {data:req.body}); //
});
app.listen(4000, ()=>{
console.log('Port 4000 has been called');
});
EDIT:
I've included the JS file which I am using to make the POST request below.
document.querySelector('#btn').addEventListener('click', Master);
async function Master(){
console.log("Button clicked")
const username = document.querySelector("#username").value;
const password = document.querySelector("#password").value;
let results = {
"username": username,
"password": password
};
console.log(results);
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(results)
};
const post = await fetch('/', options);
};
I don't know if this is a correct question lol but is it ok to have the same "/" in get and post request? Why not put something in it.
app.post("/create")
then also change this
const post = await fetch('/create', options);

Require is not defined in console. node.js js mysql

I am trying to pass some coordinates from mysql database to be marked on a map but am having trouble getting them. i have looked at a number of similar questions on stackoverflow and have not been able to find an answer. Would appreciate if someone could please point out where i have gone wrong.
getListings.js
var mysql = require('mysql');
config = {
host: 'localhost',
user: 'root',
password: 'password',
database: 'xx',
port: 'xxxx',
};
var connection = mysql.createConnection(config);
connection.connect(function (err) {
if (err) {
console.log('error connecting:' + err.stack);
}
console.log('connected successfully to DB.');
connection.query('SELECT listing_coords FROM listings', (err, rows) => {
if (err) throw err;
console.log('Data received from Db:\n');
var results = JSON.parse(JSON.stringify(rows));
module.exports = { results };
console.log(results);
});
});
Then in my script.js file i have
var { results } = require('./getListings');
console.log(results);
I am getting an error in the browser console saying "require is not defined"
I will need to figure out how to pull the coordinates from mysql in order to plot them, there has to be a way? Do i have to build an api and use ajax? Thanks in advance for any help.
have updated my getListings.js file - it now displays in the string of data i need in the browser as a raw data packet
var mysql = require('mysql');
const express = require('express');
var app = express();
const bodyparser = require('body-parser');
app.use(bodyparser.json());
config = {
host: 'localhost',
user: 'root',
password: 'password',
database: 'xx',
port: 'xxxx',
};
var connection = mysql.createConnection(config); //added the line
connection.connect(function (err) {
if (err) {
console.log('error connecting:' + err.stack);
}
console.log('connected successfully to DB.');
app.listen(5000, () => console.log('express server is running at 5000'));
app.get('/listings', (req, res) => {
connection.query(
'SELECT listing_coords FROM listings',
(err, rows, fields) => {
if (!err) res.send(rows);
else console.log(err);
}
);
});
I have been unsuccessful to get the output to run in script.js. I will post the working code when its working.
I am getting an error in the browser console saying "require is not defined"
It is because require is not an API for frontend. It should be the syntax of backend(eg. nodeJS).
Do i have to build an api and use ajax?
If you wanna to send data from frontend to backend. Using ajax is possible but the main point is you need to have a backend server(eg. using Express module for nodeJS) to connect with the database(eg. mysql, postgresSQL).
Update on 14 Feb, 2021
My practise for doing this is to use ajax to send a request to the backend server from frontend.
//frontend
$.ajax
({
url: "yourBackendServerUrl", //eg. localhost:8001/listing. Need modification based on your backend setting.
})
.done(function(data) {
console.log(data) //data should be the result from backend, then you can retrieve the data for frontend usage
});
For the CORS problem, you can install cors package. If you have a middleware in the global scope(a.k.a. app.use(cors()) ). Every time there are request, this middleware will run.
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors()) // pay attention to this line of code.
app.get('/products/:id', function (req, res, next) {
res.json({msg: 'This is CORS-enabled for all origins!'})
})
app.listen(80, function () {
console.log('CORS-enabled web server listening on port 80')
})
The solution that I got to work is as follows:
getListings.js (this was nodeJS)
var mysql = require('mysql');
const express = require('express');
const bodyparser = require('body-parser');
var app = express();
app.use(bodyparser.json());
**app.use(function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept, Authorization'
);
next();
});**// I believe this is a middleware function
config = {
host: 'localhost',
user: 'root',
password: 'password',
database: 'xx',
port: 'xxxx',
};
var connection = mysql.createConnection(config); //added the line
connection.connect(function (err) {
if (err) {
console.log('error connecting:' + err.stack);
}
console.log('connected successfully to DB.');
});
app.listen(5000, () => console.log('express server is running at 5000'));// this can be any port that isnt currently in use
app.get('/listings', (req, res) => {
connection.query(
'SELECT listing_coords FROM listings',
(err, rows, fields) => {
if (!err) res.send(rows);
else console.log(err);
}
);
});
in my script.js file i was missing the following
$.get('http://localhost:5000/listings', function (data, status) {
console.log('Cords Data', data);
I believe that is the jQuery ajax
Then in the heading of my html I needed the following
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script type = "module" defer src="script.js"></script>
thanks to everyone that helped me with this. especially #tsecheukfung01.
I dont fully understand all of the pieces so it will take me a while to fully understand this and be able to recreate this on my own. All part of the journey!

How to handle parameter in POST request in expressJS

I am working on my first project in my company and stuck at post request using expressjs.
Below is my code for post request
const express = require('express')
const app = express()
const request = require('request')
const bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: true}))
app.use(bodyParser.json())
app.post('/cruamsApi/updateUsers', (req, res) => {
const DisplayName = req.body.DisplayName
const EmployeeNumber = req.body.EmployeeNumber
const RegDate = req.body.RegDate
const url = 'http://localhost:8009/CruAmsAPI/Employee'
request (
{
url: url,
json: true,
body: {
"EmployeeNumber": EmployeeNumber,
"DisplayName": DisplayName,
"RegDate": RegDate
}
},
function (error, response, body) {
if(!error) {
res.send(response)
} else {
res.send(error)
}
}
)
})
app.listen(PORT, () => {
console.log('server is listening port ' + PORT)
})
When I make a POST request, it is keep returning "EmployeeNumber parameter is required" error message from an API. I tried to double quote the keys "EmployeeNumber" but still having a same issue. Included headers too but didn't really work. POST request does work in POSTMAN.
Have you tried to send the EmployeeNumber in your request?
If it works in Postman, it should work. I think that your issue is in your front-end which doesn't send any EmplyeeNumber in the request.

Node JS POST request returning undefined body

Quite new to Node JS and I am trying to post to a specific URL and retrieve the data.
I am using postman to do this but every time I post to it the response data is undefined but the status code is 200.
I have added body-parse as suggested but still no joy.
I will post my server code and request below.
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = process.env.PORT || 5000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/api/hello', (req, res) => {
res.send({ express: 'Hello From Express' });
});
app.post('/api/save-json', (req, res) => {
console.log(req);
res.send(
`I received your POST request. This is what you sent me: ${req.body.json}`,
);
});
app.listen(port, () => console.log(`Listening on port ${port}`));
My postman request is:
{
"body" :
{
"json": "some data"
}
}
Any ideas?
body is the property in the req object containing the HTTP request body (which is set by body-parser), since you're sending in an object called body you'll need to access it like this: req.body.body.json

Categories