Node, how can I send response headers on a node/express app? - javascript

I have a basic server. One of my tests that I need to pass is to send the response header of 200. I added the code for the server as it is now. But not sure how to send response headers. Thanks for any help you may be able to provide!
var express = require('express');
var bodyParser = require('body-parser');
var Users = require('./models/users');
var app = express();
app.use(bodyParser.json());
// YOUR CODE BELOW
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var router = express.Router();
// middleware for all requests:
router.use(function(req, res, next){
console.log('we out here babay!');
// get to the next route and ensures we don't stop here.
next();
})
router.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
});
app.use('/api', router);
// Do not touch this invocation of the `listen` method
app.listen('8888', function () {
console.log('listening on 8888');
});
// Do not touch the exports object
module.exports = app;

Use res.status(CODE) method!
res.status(200).json({ message: 'hooray! welcome to our api!' });
As highlighted in comments by jfriend00, default status code is 200 so any regular response will already be 200 but for other codes like 500 or 404, if your client side is considering it while reading the response, you can use res.status() method.

Related

Node.js express - body of POST request is always empty

I am trying to read the body of POST request using Express in Node.JS framework. I send a HTTP POST request using HTML form. I detected a POST request on WireShark with the following data:
This shows that the request is sent successfully. I expected JSON format, which is the one that Express successfully parsed for me, but this format just doesn't seem to work no matter what I tried. My current implementation goes like this:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var jsonParser = bodyParser.json()
//Import static files
app.use(express.static('../public'))
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/', jsonParser, (req, res) => {
console.log(req.body);
res.send(200);
});
app.listen(port, () => console.log("Server started"));
No matter what I try from other posts, it still does not seem to return me any data.
Does anyone have an idea how to fix this problem?
Why to you use 'jsonParser' in the app route? Try something like:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/post-test', (req, res) => {
console.log('Got body:', req.body);
res.sendStatus(200);
});

Express.js Handle unmached routes

Fellows I develop a Rest API and I want when a route does not exist to send a custom message instead of an html one that express.js sends by default. As fas as I searched I could not find a way to do that.
I tried to do:
app.all("*",function(req,res){
res.status(404)
res.header("Content Type","application/json")
res.end(JSON.stringify({message:"Route not found"}))
});
But it matches and all already implemented methods. I want only the unmached one to get handled by my app.
Edit 1
For each enndpoint I create a seperate file having the following content: eg. myendpoint.js
module.exports=function(express){
var endpoint="/endpoint"
express.get(endpoint,function(req,res){
res.end("Getting data other message")
}).post(endpoint.function(req,res){
res.end("Getting data other message")
}).all(endpoint,function(req,res){
res.status(501)
res.end("You cannot "+res.method+" to "+endpoint)
})
}
An in my main file I use:
var endpoint=require('myendpoint.js')
var MyEndpointController=endpoint(app)
app.all("*",function(req,res){
res.status(404)
res.header("Content Type","application/json")
res.end(JSON.stringify({message:"Route not found"}))
});
1.Declare all of your routes
2.Define unmatched route request to error respose AT the END.
This you have to set it in the app. (app.use) not in the routes.
Server.js
//Import require modules
var express = require('express');
var bodyParser = require('body-parser');
// define our app using express
var app = express();
// this will help us to read POST data.
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8081;
// instance of express Router
var router = express.Router();
// default route to make sure , it works.
router.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
});
// test route to make sure , it works.
router.get('/test', function(req, res) {
res.json({ message: 'Testing!' });
});
// all our routes will be prefixed with /api
app.use('/api', router);
// this is default in case of unmatched routes
app.use(function(req, res) {
// Invalid request
res.json({
error: {
'name':'Error',
'status':404,
'message':'Invalid Request',
'statusCode':404,
'stack':'http://localhost:8081/'
},
message: 'Testing!'
});
});
// state the server
app.listen(port);
console.log('Server listening on port ' + port);
Please note : I have prefix '/api' in my routes.
Please try http://localhost:8081/api
You will see '{"message":"hooray! welcome to our api!"}'
When you try http://localhost:8081/api4545 - which is not a valid route
You would see the error message.
First you need to define all existing routes then at last you have to define no
route. order is very important
// Defining main template navigations(sample routes)
app.use('/',express.static(__dirname + "/views/index.html"));
app.use('/app',express.static(__dirname + "/views/app.html"));
app.use('/api',express.static(__dirname + "/views/api.html"));
app.use('/uploads',express.static(path.join(__dirname, 'static/uploads')));
//If no route is matched by now, it must be a 404
app.use(function(req, res, next) {
res.status(404);
res.json({status:404,title:"Not Found",msg:"Route not found"});
next();
});
Can't post as comment (reputation is too low ...) but did you define this route after all your other paths ?
The order is really important, you should first define all your routes and then have this one.
on my case for the safetyness of my routes life cycle I used this **/** or */*, *(asterisk) operator stands for all, and here's my example.
app.use('**/**',express.static(path.join(__dirname, './public/not-found/index.html')));

ExpressJS Route hanging and timing out

I have a simple example that I am following.
For some reason the request always times out, wondering if you have any ideas why this could be happening.
// server.js
// BASE SETUP
// =============================================================================
// call the packages we need
var express = require('express'); // call express
var app = express(); // define our app using express
var bodyParser = require('body-parser');
// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
var port = process.env.PORT || 8080; // set our port
//load the model
var Bear = require('./models/bear');
// ROUTES FOR OUR API
// =============================================================================
var router = express.Router(); // get an instance of the express Router
// middleware to use for all requests
router.use(function(req, res, next) {
// do logging
console.log('Something is happening.');
next(); // make sure we go to the next routes and don't stop here
});
router.route('/bears')
// create a bear (accessed at POST http://localhost:8080/api/bears)
.post(function(req, res) {
var bear = new Bear(); // create a new instance of the Bear model
bear.name = req.body.name; // set the bears name (comes from the request)
// save the bear and check for errors
bear.save(function(err) {
if (err)
res.send(err);
//res.json({ message: 'Bear created!' });
res.json({ message: 'hooray! welcome to our api!' });
});
});
// test route to make sure everything is working (accessed at GET http://localhost:8080/api)
router.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
});
// more routes for our API will happen here
// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', router);
// START THE SERVER
// =============================================================================
app.listen(port);
console.log('Magic happens on port ' + port);
Let me know what you think. Essentially I can do GETS no problem, but when I get to /bears and do a POST x-www-form-urlencoded with a param name 'Klaus' it simply hangs. I can't understand why.
Any suggestions much appreciated.
Many thanks for your help.

How to handle "Cannot <METHOD> <ROUTE>" in Express?

As a minimal example, consider following code:
var express = require('express');
var bodyparser = require('body-parser');
var app = express();
app.use(bodyparser.json());
app.use(errorhandler);
function errorhandler(err, req, res, next) {
res.setHeader('Content-Length', 0);
res.status(500).end();
}
app.post('/example', function(req, res) {
res.setHeader('Content-Length', 0);
res.status(200).end();
});
var server = app.listen(3000, function() {
console.log('server listening on http://%s:%s ...', server.address().address, server.address().port);
});
When I, for example, now try a PUT on /example, I get a Cannot PUT /example message with 404 status code. The same is true for all other routes and methods I did not declare. My error handler is only getting called on actual errors within a route or the body parser itself.
Is there a way to handle them by myself? I am using Express4.
Define a general handler with no route after all other use/get/post/etc:
app.use(function(req, res, next){
res.status(404);
res.render(...);
}

Access session object in Express middleware

This is my Express middleware stack:
var server = express()
.use(express.cookieParser())
.use(express.session({secret: 'Secret'}))
.use(express.bodyParser())
.use(function printSession(req, res, next) {
console.log(req.session.user);
next();
})
.use(express.static('./../'));
and here are two routes:
server.post('/setSession', function (req, res) {
req.session.user = 'admin';
}
server.post('/getSession', function (req, res) {
console.log(req.session.user);
}
Now the session management in the route handlers work find. I can set session.user and it will persist for the subsequent requests in the same session, as confirmed by getSession. However, the middleware function printSession always prints undefined.
How can I access the populated session object in the middleware?
This program works fine. Before I access /setSession, the middleware prints after session: undefined. Once I GET /setSession, it prints after session: admin. As long as the browser you are testing with (not curl) stores and sends the session cookies, this will work as expected.
var express = require('express');
var server = express();
server.use(express.cookieParser());
server.use(express.session({secret: 'SEKRET'}));
server.use(function (q,r,n) {console.log('after session:', q.session.user);n();});
server.get('/', function (q,r,n) {r.send("you got slashed");});
server.get('/setSession', function (req, res) {
console.log("logging admin in via /setSession");
req.session.user = 'admin';
res.send("admin logged in");
});
server.listen(3000);
There must be something wrong with your settings. The following example, that is very similar to your code but uses GET instead POST, works fine for me
app.configure(function(){
// ...
app.use(express.cookieParser('your secret here'));
app.use(express.session());
app.use(function(req, res, next) {
console.log(req.session.user + ' from middleware');
next();
});
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
and
app.get('/getSession', function(req, res) {
console.log(req.session.user);
res.send('awesome');
});
app.get('/setSession', function(req, res) {
req.session.user = 'admin';
res.send('done');
});
Now when you do the following everything works as expected
GET /getSession => undefined from middleware, undefined
GET /setSession => undefined from middleware
GET /getSession => admin from middleware, admin

Categories