SK1dev
SK1dev

Reputation: 1139

Node/Express: GET request - 304

I'm making a GET request to get user (by user id) but I'm receiving a 304 status code.

How would I solve this?

routes/user.js

...
router.get('/secret/:userId', requireSignin, (req, res) => {
  console.log('id retrieved')
})

router.param('userId', userById)

controllers/user.js

const User = require("../models/User");

exports.userById = (req, res, next, id) => {
    User.findById(id).exec((err, user) => {
        if (err || !user) {
            return res.status(400).json({
                error: 'User not found'
            });
        }
    res.json(user)
    console.log("id retrieved successfully")
        next();
    });
};
 

controllers/auth.js

exports.requireSignin = expressJwt({
    secret: process.env.JWT_SECRET,
    algorithms: ['HS256'],
    userProperty: 'auth'
});

exports.isAuth = (req, res, next) => {
    let user = req.profile && req.auth && req.profile._id == req.auth._id;
    if (!user) {
        return res.status(403).json({
            error: 'Access denied'
        });
    }
    next();
};

Upvotes: 0

Views: 521

Answers (3)

Ducnb
Ducnb

Reputation: 43

in your "controller/user.js" you need change from:

res.json(user)

to

req.profile = user

Upvotes: 0

Ernesto
Ernesto

Reputation: 4252

because you have 4 parameters in yow route. they have to be three.

  • path.
  • array of middlewares.
  • endpoint.
router.get('/myblog/:userId', [requireSignin, isAuth], listPostsBySignedInUser)

thats for the router. also the middlewares syntaxis is

function (req, res, next) {...}

if you have a middleware with 4 parameters such as

exports.userById = (req, res, next, id) => {

to you it looks like that, but for express and its conventions it looks like this

exports.userById = (error, request, response, next) => {}

not only on express but on JS every first parameter will contain the error

Upvotes: 0

Naor Levi
Naor Levi

Reputation: 1813

from: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/304

The HTTP 304 Not Modified client redirection response code indicates that there is no need to retransmit the requested resources. It is an implicit redirection to a cached resource.

It means that the server tells the client that he can use a cached entity. It saved a lot of transportation.

It is done behind the scenes even if you return 200 (res.json is 200 status code by default) explicitly.

Upvotes: 1

Related Questions