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.
Related
I'm building an API for my web app and I was able to successfully send requests to the routes in Post.js when they only had url params. But when I try to create a route like '/allposts' (the last endpoint in Post.js) , I receive a 404 error message on postman. Here's my code:
router.post('/', (req, res) => {
// Endpoint 1 code here
})
router.get('/:id', (req, res) => {
// Endpoint 2 code
})
// This is the route that I can't to send requests to
router.get('/ap', async(req, res) => {
try{
const ap = await P.find()
res.send(ap)
} catch(error){
log(error)
res.status(500).send("error")
}
})
server.js
const express = require('express')
var cors = require('cors')
const fs = require('fs');
const path = require('path');
var app = express()
app.use(express.static(path)
app.use(cors())
const bodyParser = require('body-parser')
app.use(bodyParser.json());
var p = require("./routes/P.js");
app.use('/post', p);
const PORT = process.env.PORT || 3001
app.listen(port, () => {
log(`Listening on port ${PORT}...`)
});
When I send a request to http://localhost:3001/post/ap, I'm getting the a 404 Not Found error, but the first two routes work fine. It seems like routes with url params work, but the allposts route does not. Any help would be greatly appreciated. Thanks.
Main problem is the order of the routes.
router.get('/:id') will be initialized before router.get('/allposts'). So when you want to access /allposts the first router will catch it.
You need to switch the init order.
First router.get('/allposts') then router.get('/:id').
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?
Though my rendering path is correct when I hit http://localhost:4444/admin/posts/create it shows some error like
Error: Failed to lookup view "/admin/posts/create" in views directory "D:\node practise\CMS\views"
app.js file is like
const express = require('express');
const app = express();
const path = require('path');
const exphbs = require('express-handlebars');
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/cms', { useNewUrlParser: true })
.then(db => {
console.log('MONGO CONNECTED!');
})
.catch(error => {
console.log('MONGO NOT CONNECTED!');
})
//making app to use static file
app.use(express.static(path.join(__dirname, 'public')));
//define template engine
app.set('view engine', 'handlebars');
//set default engine
app.engine('handlebars', exphbs({defaultLayout: 'home'}));
//load routes
const home = require("./routes/home/index");
const admin = require("./routes/admin/index");
const posts = require("./routes/admin/posts");
//use routes
app.use(home);
app.use("/admin", admin);
app.use("/admin/posts", posts);
//setting up server
app.listen(4444, () => {
console.log('Listening....');
});
I have posts.js that handles this route like
const express = require("express");
const router = express.Router();
router.all('/*', (req, res, next) => {
req.app.locals.layout = 'admin';
next();
})
router.get('/', (req, res) => {
res.send('It works!');
})
router.get('/create', (req, res) => {
res.render('/admin/posts/create');
})
module.exports = router;
And I have my views folder structure as
What may be the cause of error? When I try to send response it works but when I try to render the view it shows error.
Can you try res.render('admin/posts/create');?
If the view folders is set properly like this: app.set('views', './views'), you should be able to resolve simple view name like res.render('myview') under ./views folder
I created a simple server using expressjs and have post method but I got strange response to post article and I don't know why it happened. Could anyone mind helping me?
my expected is a JSON format.
Here is my app.js file
const express = require('express');
const mongoose = require('mongoose');
const articleModel = require('./models/article');
const bodyParser = require('body-parser');
enter code here
const db = mongoose.connect('mongodb://0.0.0.0:27017/bbs-api');
const app = express();
const port = process.env.PORT || 3000;
//support parsing of application/x-www-form-urlencoded post data
app.use(bodyParser.urlencoded({extended:true}));
// support parsing of application/json type post data
app.use(bodyParser.json());
const bbsRouter = express.Router();
bbsRouter.route('/articles').post( (req, res) => {
console.log(req.body);
// const newArticle = new articleModel(req.body);
// newArticle.save();
// res.status(201).send(newArticle);
res.send(req.body);
});
app.use('/api', bbsRouter);
app.get('/', (req, res) => res.send('Hello World!'))
app.listen(port, () => console.log('Example app listening on port 8000!'))
My postman. I log request body out but it is not as my expectation.
if you are sending form data(application/x-www-form-urlencoded) the you can do
bbsRouter.route('/articles').post( (req, res) => {
console.log(req.params);
// const newArticle = new articleModel(req.body);
// newArticle.save();
// res.status(201).send(newArticle);
res.send(req.params);
});
You're sending the wrong request body via postman, your body should be JSON format, not form data
Try removing body-parser and use middlewares directly from express and set urlencoded to false:
app.use(express.urlencoded({extended:false}));
// support parsing of application/json type post data
app.use(express.json());
See here urlencoded option documentation
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");
});