I'm fairly new to web development and have just started on node and express 4.9.0.
Already went through some tutorials and played around with the API. From what I understand, http protocol and request urls are the backbone of a web app. For example, we have to manipulate the url to redirect the user to another page or upload files. POST is for submitting data and GET is for requesting data. Also, response.send()
is for sending server's response back to client. We also must have response.end()
at the end, according to nodejs docs (I assume this is the same for express).
Coming to the express part - here are some examples I tried and do not understand why they're not working:
1. Calling response.send() in two places
Motivation: To find out what exactly does response.send() do, and can I send different parts of information to client in different places.
I expected express to process the first app.get, then follow the next() to our next app.get. Finally, output "Welcome to the homepage!" and "Welcome to the second page!". However, the app crashed with net::ERR_EMPTY_RESPONSE
. Why is that so?
var express = require("express");
var http = require("http");
var app = express();
app.all("*", function(request, response, next) {
response.writeHead(200, { "Content-Type": "text/plain" });
next();
});
app.get("/", function(request, response, next) {
response.send("Welcome to the homepage!");
next();
});
app.get("/", function(request, response) {
response.end("Welcome to the second page!");
});
app.get("*", function(request, response) {
response.end("404!");
});
http.createServer(app).listen(1337);
2. When to use app.get and app.set?
Tried interchanging them and they often have similar behaviours.
For instance, if we remove the erronous response.send()
in the first example, it successfully finds the next app.get
with parameter "/"
. This also works if we replace app.get
with app.set
3. Redirecting
Tried redirecting to another external site, or another page of my site, but got net::ERR_EMPTY_RESPONSE
app.all("*", function(request, response, next) {
response.writeHead(200, { "Content-Type": "text/plain" });
next();
});
app.get("/", function(request, response) {
response.redirect("http://google.com");
//also does not work with response.redirect("/about);
});
app.get("/about", function(request, response) {
response.end("about page");
});
4. Why do we need express routers? Read that there's been a breaking change in routers from express 3.x to 4.x. Using 4.9.0 here.
var router = express.Router([options]);
The synatx and api for routers is almost the same as using plain old var app = express();
The documentation also says Routers behave like middleware themselves and can be ".use()'d" by the app or in other routers.
Isn't the normal express already a middleware in itself, and we can use it to do routing?