How to send response from a post request in node.js? - node.js

I am trying to send response from post requests and on internet I have seen I have to use res.end but it does not seem to work in my case. I have done post requests in the past succesfully but now I need to do them without loading the website, so it has to be asynchronous for each post request.
This is what I have:
Game.js:
textModalContent1.addEventListener("click", () => {
//Ask for username
let username = prompt("Enter your new username");
$.post("/addUser",{username: username}, function(data){ //I use jQuery for post requests
console.log(data);
});
});
index.js:
const express = require('express');
const app = express();
app.use('/assets', express.static('./assets/'));
var bodyParser = require('body-parser')
app.use( bodyParser.json() );
app.use(bodyParser.urlencoded({
extended: true
}));
app.get('/', function (req, res) {
res.render('./index.ejs', {});
});
app.post('/addUser', function(req, res) {
//console.log(req.body.username)
res.end("hello"); //this should send "hello" to the client
});
app.listen(process.env.PORT || 14532);
Each time I enter a username, should appear "hello" on my web browser console but it does not.
What am I doing wrong?

Related

axios post request from frontend not recieving in node js backend

I am trying to learn node js. I am tryng to put a post request from axios by frontend but node js is responding with empty object.
Here is the code
node js
var express = require("express");
var app = express();
var cors = require("cors");
app.use(cors());
var bodyParser = require("body-parser");
var urlencodedParser = bodyParser.urlencoded({ extended: false });
// This responds with "Hello World" on the homepage
app.get("/", function (req, res) {
console.log("Got a GET request for the homepage");
res.send("Hello GET");
});
app.post("/", urlencodedParser, function (req, res) {
console.log(req.body);
res.send("Hello GET");
});
var server = app.listen(8081, function () {
var host = server.address().address;
var port = server.address().port;
console.log("Example app listening at http://%s:%s", host, port);
});
frontend
axios.post("http://localhost:8081/", { body: "dan" })
.then((e) => console.log(e))
The response is an empty object.
What should I do?
By default your axios code:
axios.post("http://localhost:8081/",{body:"dan"}).then((e) => console.log(e))
will send the body of the POST request as JSON. Quoted directly from the axios doc.
By default, axios serializes JavaScript objects to JSON
So, you need JSON middleware on your Express server to read and parse that JSON body. Without middleware that is looking for that specific content-type, the body of the POST request will not be read or parsed and req.body will remain empty.
app.post('/', express.json(), function (req, res) {
console.log(req.body);
res.send('Hello POST');
});
Note, there is no need to separately load the body-parser module as it is built-in to Express.
Or, if you want the request to be sent as application/x-www-form-urlencoded content-type, then you would need to encode the data that way and send it as the data in your axios request and set the content-type appropriately.
These request bodies can be handled by the express.urlencoded() middleware in the same way as express.json().
You should use bodyParser.json(), to get the data sent in req.body.
var bodyParser = require('body-parser');
app.use(bodyParser.json());
We should parse request body before access it using middleware in the following way
app.use(bodyParser.json());

How are the req and res objects created in Node.js?

I understand what the req and res objects contain, what they are used for, and when they are created, but I was wondering how they are created.
The req and res objects that you are referring to come from an npm package called express. Express is a lightweight package that allows you to handle HTTP requests on your node server.
Below is a small example of how to use the package with some example HTTP endpoints.
In the example, I also use a package called 'body-parser' this package is used to parse any HTTP requests with a JSON body. The package puts the parsed body into the req object at the key body, as can be seen in the code example.
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/', (req, res) => {
// Handle GET / request here
});
app.post('/', (req, res) => {
// Handle POST / request here
// Get body of request
var body = req.body;
});
app.listen(8080, () => console.log('Listening on port 8080'));
req and res are the component of Express framework of Node package manager(npm) and is used to respond as per the request created by the user.
//To print Date as string
const express = require("express");
const bodyparser = require("body-Parser");
const app = express();
app.get("/", function(req, res) {
var today = new Date();
var options = {
weekday: "long",
year: "numeric",
month: "long",
day: "numeric",
};
var day = today.toLocaleDateString("en-US", options);
res.render("list", {
kindOfDay: day
});
});
app.post("/", function(req, res) {
var item = req.body.selectSection;
items.push(item);
res.redirect("/");
});
app.listen("3000", function() {
console.log(" the server is runnimg in port 3000");
});

Query parameters in Express

I am trying to get access to query parameters using Express in Node.js. For some reason, req.params keeps coming up as an empty object. Here is my code in server.js:
const express = require('express');
const exphbs = require('express-handlebars');
const bodyParser = require('body-parser');
const https = require('https');
//custom packages ..
//const config = require('./config');
const routes = require('./routes/routes');
const port = process.env.port || 3000;
var app = express();
//templating engine Handlebars
app.engine('handlebars', exphbs({defaultLayout: 'main'}));
app.set('view engine', 'handlebars');
//connect public route
app.use(express.static(__dirname + '/public/'));
app.use(bodyParser.json());
//connect routes
app.use('/', routes);
app.listen(port, () => {
console.log( 'Server is up and running on ' + port );
});
And here is my routes file:
//updated
const routes = require('express').Router();
routes.get('/', (req, res) => {
res.render('home');
});
routes.post('/scan', (req, res) => {
res.status(200);
res.send("hello");
});
routes.get('/scanned', (req, res) => {
const orderID = req.params;
console.log( req );
res.render('home', {
orderID
});
});
module.exports = routes;
When the server is up and running, I am navigating to http://localhost:3000/scanned?orderid=234. The console log that I currently have in the routes.js file is showing an empty body (not recognizing orderid parameter in the URL).
orderid in the request is query parameter. It needs to be accessed via req.query object not with req.params. Use below code to access orderid passed in the request:
const orderID = req.query.orderid
Now you should be able to get 234 value passed in the request url.
Or try replacing the code for route /scanned with below:
routes.get('/scanned', (req, res) => {
const orderID = req.query.orderid
console.log( orderID ); // Outputs 234 for the sample request shared in question.
res.render('home', {
orderID
});
});
The reason that req.body keeps coming up as an empty object is that in get requests, such as those made by the browser on navigation, there is no body object. In a get request, the query string contains the orderid that you are trying to access. The query string is appended to the url. Your code can be rewritten as below:
routes.get('/scanned', (req, res) => {
const orderID = req.query.orderid
console.log( req );
res.render('home', {
orderID
});
});
A note, though, is that if you have AJAX posts firing within your client side code, your req.body will not be empty, and you can parse it as you would normally.

BodyParser data is undefined after AJAX call

The body parser body is {}. I've already done research and made sure that my ajax data key is set correctly as well as make sure the middleware is set up correctly as well. Here is my frontend ajax call
$.ajax({
type:"GET",
url:"/api",
data: {course:"MATH-226"},
success: function(data){ alert(data);}
});
And here is my backend server.js file:
'use strict'
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const alg = require('./app/algorithm.js');
const app = express();
app.use('/', express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.get('/api', (req, res) => {
console.log(req.body);
alg.create(req.body.course, answer => res.send(answer));
});
let server = app.listen(3000, () => {
let host = server.address().address;
let port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
You are using a GET request, so it's probably not being sent. If you need to send something, you can attach it as a header or include it in the query string of the url. If you want to send data, I would use a POST request.
Check out this article
How to send data in request body with a GET when using jQuery $.ajax()

post using restler and node.js is not returning

I am trying to post using restler and return the response to client but response never returns .Below is code I am using and response is just hanging
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var rest = require('restler');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = 3001; // can also get it from process.env.PORT
var router = express.Router();
//this is like interceptor for every route to validate all requests, logging for analytics
router.use(function (req, res, next) {
console.log('route intercepted');
next(); // make sure we go to the next routes and don't stop here
});
router.get('/', function(req, res) {
res.json({ message: "welcome to restful node proxy layer to business processes" });
});
router.route('/someroute').post(function(req, res) {
rest.postJson('http://localhost/api/sg', req.body).on('complete', function(data, response) {
console.log(response);
}
).on('error', function(data, response) {
console.log('error');
});
});
app.use('/api', router); //all routes are prefixed with /api
app.listen(port);
console.log("server is running magic happens from here");

Resources