There are obviously duplicate questions but the answers didn't help me. Either there is something fundamental that I just don't understand yet as a beginner in nodeJS and Express or something weird is happening.
I have two Express routes, the first one works perfectly fine. But as soon as I started working on the second one I immediately encountered the problem when trying to use 'res' to send back a HTTP status code.
server.js with everything unrelated redacted:
const express = require('express')
const session = require('express-session')
const MySQLStore = require('express-mysql-session')(session)
const db = require('./database')
const route1 = require('./routes/route1')
const route2 = require('./routes/route2')
const sessionStore = new MySQLStore({}, db)
const app = express()
app.use(express.json())
app.use(session({
// session settings
}))
// Routes
app.use('/api/route1', route1)
app.use('/api/route2', route2)
app.listen(process.env.PORT || 8000)
route1.js (with everything unrelated redacted):
const express = require('express')
const db = require('../database')
const router = express.Router()
// Middleware
function validateData(req, res, next) {...}
async function validateUser(req, res, next) {...}
// POST data to db
router.post('/', validateData, validateUser, async (req, res) => {
try {
const results = await db.query(
// Querry to db
)
} catch(err) {
// Handle error
}
res.status(200).end()
})
module.exports = router
route2.js - where error happens (with everything unrelated redacted):
const express = require('express')
const db = require('../database')
const router = express.Router()
router.get('/', (req, res) => {
res.statusCode(200).end() // TypeError: res.statusCode is not a function
})
module.exports = router
CodePudding user response:
It says it correctly.
res.statusCode
is not a function, it is Node.js native variable: https://nodejs.org/api/http.html#responsestatuscode
Express have function res.status(statusCode)
, i.e. res.status(200);
: https://expressjs.com/en/api.html#res.status