I am writing a query controller in pure Node js. Why is the error "response.status is not function" coming to the console?
const Admins = require('../models/admins')
const Films = require('../models/films')
const Categories = require('../models/categories')
module.exports = function requestController(request, response){
if(request.method === 'GET' && request === '/admins/all'){
Admins.findAll()
.then(()=>{
response.status(200).json()
})
}else{
console.log(response)
response.status(400).json()
}
}
I tried changing the names and displaying the response in the console. response didn’t really have a status function.
the function of creating a server and calling the main-contrller
const db = require('./base');
const http = require('http');
const port = 3500;
const Sequelize = require('sequelize');
const requestController = require('./controllers/main-controller');
http.createServer(function(request, response){
console.clear();
console.log('=================================');
console.log('|| SERVER WORKED ||');
console.log('=================================');
requestController(request,response);
response.end('Server Ready');
}).listen(port);
2
Answers
You are using express syntax in native http, so it does not have
status
orjson
functions.You can use
end
,writeHead
,statusCode
instead.Refer this DOC
The error
response.status
is not a function occurs because the response object in the Node.js http module does not have a status method.Remember, when you’re not using a framework like Express.js that abstracts these details away, you need to manually handle HTTP status codes, headers, and response bodies with the native Node.js http module methods.
In this corrected version, I’ve replaced
response.status(200).json()
with the appropriate method for setting the status code and headers in plain Node.js:response.writeHead(statusCode, headers)
: This method sets the response status code and headers. For example,response.writeHead(200, { 'Content-Type': 'application/json' })
sets the status code to 200 and the Content-Type header toapplication/json
.response.end(data)
: This method sends the response data and signals to the server that all of the response headers and body have been sent. For example,response.end(JSON.stringify({ message: 'Success' }))
sends a JSON response.