Reputation: 129
I have a simple nodejs app that I'm trying to send a "page not found" message if the url is invalid.
const http = require("http");
const port = 4098;
let app = http.createServer((request, response) => {
let url = request.url;
switch (url) {
case "/":
getStaticFile(response, "./public/home.html");
break;
case "/contact":
getStaticFile(response, "./public/contact.html");
break;
default:
response.send("Oops...Page Not Found!");
break;
}
});
function getStaticFile(response, pathToFile) {
fs.readFile(pathToFile, function(error, data) {
if (error) {
response.writeHead("500", { "Content-Type": "text/plain" });
response.end("500 - Internal Server Error");
}
if (data) {
response.writeHead("200", { "Content-Type": "text/html" });
response.end(data);
}
});
}
app.listen(port, () => {
!console.log(`Listening to connections on port ${port}`);
});
I'm passing the response to the getStaticFile but I'm getting a response.send()is not a function. What could be my issue?
Upvotes: 0
Views: 3720
Reputation: 319
You have probably created an HTTP server based on the http module.
response, which is a http.ServerResponse instance, does not have a .send
method. It does, as you found out, have a .end
method, though.
My guess is that you have seen some Express code. Express is a framework to build HTTP servers, and it provides additional functionality on top of the regular http module.
One of those additional functions is a .send method for HTTP response instances:
var express = require('express');
var app = express();
var server = app.listen(3000);
app.get('/', function(request, response) {
response.send('hello world!');
});
Upvotes: 5