What happens after Express redirect? - express

Given a simple toy example:
var express = require("express");
var app = express();
app.get('/', function(req, res) {
res.redirect("https://www.google.com"); // <-- (*)
console.log("After redirect");
});
var server = app.listen(14000, 'localhost', function() {
var host = server.address().address;
var port = server.address().port;
console.log('Test listening on port 14000.');
});
At the location marked with (*), what happens there? Is a 3XX Status Code returned while the server runs the following statements? Or is the 3xx status code only returned after the block finishes?
Is this handled differently in other frameworks, i.e. Django?

Related

Switching from working node js socket io serialport to node express router how to?

I am new to node express (started with node long time ago but didn't do much) and I would like to learn how to use it. I am going through some of my older work and reading lots of tutorials but I just can't seem to get this one working.
I have this app that reads data from some sensors on serial port and sends it to sesors.ejs. I would like to reprogram it in express. I have the sensor reading in terminal but not in ejs.
old (working) app.js
var http = require('http');
var fs = require('fs');
var url = require('url');
var path = require('path');
const { SerialPort } = require('serialport')
const { ByteLengthParser } = require('#serialport/parser-byte-length')
const port = new SerialPort({ path: 'COM4', baudRate: 9600 })
const parser = port.pipe(new ByteLengthParser({ length: 30 }))
var sensors = fs.readFileSync('views/sensors.ejs');
var app = http.createServer(function(req, res){
res.writeHead(200, {'Content-Type':'text/html'});
res.end(sensors);
});
var io = require('socket.io').listen(app);
io.on('connection', function(data){
console.log
});
parser.on('data', function(data){
console.log(data.toString("UTF8"));
io.emit('data', data.toString("UTF8"))
});
app.listen(3000);
old (working) sensors.ejs
<script>
var socket = io();
socket.on('data', function(data){...}
</script>
This works great.
I went through several express routing tutorials but I don't know how to send io data to router.
I have c/p most of the code from old app.js to new sensor.js in routes dir, without fs, app.listen etc. I have c/p sensors.ejs to views folder.
In new app.js I have:
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var sensorsRouter = require('./routes/senzori');
var app = express();
app.set('views', path.join(\__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(\__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/senzori', sensorsRouter);
index.ejs and users.ejs (fetch mysql data) are working (express is installed and working)
Thanks
I have found the solution. If anyone else with my level of "knowledge" needs the solution, here it is:
I have moved reading serial port to bin/www
The only code in sensors.js is:
router.get('/', function(req, res, next) {
res.render('sensors');
});

router.route() doesnt want to work at all

I am trying to run router.route() with the following code
const express = require('express');
const app = express();
const router = express.Router();
router.route('/test').get(function (req, res, next) {
res.send('You have reached localhost:9000/test');
next();
});
app.listen(9000, () => {
console.log('Running on port 9000');
});
But it doesn't seem like anything is happening at all. Regardless of what I do, localhost:9000/test will not return anything Cannot GET /test. I don't understand what I'm doing wrong. Thanks in advance
You have to hook the router into your app with app.use():
const express = require('express');
const app = express();
const router = express.Router();
router.get('/test', function (req, res, next) {
res.send('You have reached localhost:9000/test');
});
app.use(router); // <=== add this
app.listen(9000, () => {
console.log('Running on port 9000');
});
Your original code creates a router object, but that router object is not hooked up to any web server yet. Using app.use(), you can hook it up to your web server so that it actually gets a chance to see the incoming requests.
Also, do not call next() after you call res.send(). Pick one of the other. Once you send a response, you do not want to continue routing to other routes because that will often try to then send another response, but you can only send one response to a given incoming http request.
You can simply use the Router().get(...) function instead.
The <Router>.get('/path', function() {...}); function will listen for incoming traffic to the path /path and then fire the callback function with the parameters request, response and next.
Example:
router.get('/test', function (req, res) {
res.send('You have reached localhost:9000/test');
});
Full example:
const express = require('express');
const app = express();
const router = express.Router();
router.get('/test', function (req, res) {
res.send('You have reached localhost:9000/test');
});
app.listen(9000, () => {
console.log('Running on port 9000');
});
Note: Using the next() function after sending a response to an incoming HTTP request will result in an error.

Socket Programming res.sendFile is not a function

res.sendFile is not a function.
The following is my server js code
var app = require('express')();
var http = require('http').Server(app);
var fs = require('fs');
var io = require("socket.io")(http);
var users = {};
app.get('/', function(req, res) {
res.sendFile(__dirname + '/client.html');
});
app.listen(3000)
io.on("connection", function (client) {
client.on("join", function (name) {
users[client.id] = name;
client.emit("update", "Connected to Server");
socket.sockets.emit("update", name + " has entered the confession room");
socket.sockets.emit("update-users", users);
});
client.on("send", function (msg) {
socket.sockets.emit("chat", users[client.id], msg);
});
client.on("disconnect", function () {
socket.sockets.emit("update", users[client.id] + " has left the confession room");
delete users[client.id];
socket.sockets.emit("update-users", users);
});
});
Things I have tried:
- Checking the order of the parameter.
- Installing express module.
You have duplicate servers with these two lines of code and you're passing the one to socket.io that you never start:
var http = require('http').Server(app); // one on port 80
app.listen(3000); // one on port 3000
Remove the first one, then modify your code as shown below. And, make sure you're connecting on port 3000 where the Express server and socket.io severs are.
Or, if you want the server and socket.io to be on port 80, then change to:
const server = app.listen(80);
So, you should end up with this:
const app = require('express')();
const fs = require('fs');
const users = {};
app.get('/', function(req, res) {
res.sendFile(__dirname + '/client.html');
});
const server = app.listen(3000);
const io = require("socket.io")(server);
// various socket.io code here

Error: listen EACCES 0.0.0.0:8080 but can't find PORT?

I have this code currently:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var sessionManager = require("./SessionRaterBL");
sessionManager.CreateTestData();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8080;
var router = express.Router();
var sessionRouter = express.Router();
router.get('/', function(req, res) {
res.json({ message: 'API Session Rater Backend' });
});
sessionRouter.get("/",function(req,res){
res.json(sessionManager.GetSessions())
});
sessionRouter.get("/:id",function(req,res){
var session;
try{
session = sessionManager.GetSession(req.param.id);
res.json(session);
}catch(ex){
res.status(404).send(ex);
}
});
app.use('/api', router);
app.use('/api/sessions',sessionRouter);
app.listen(port);
console.log('Magic happens on port ' + port);
When executing the program I get the above named error.
So I did a netstat -anb I get this: all ports
So I tried finding the PORT 8080 or 80 but I just could not find it.
If I execute my Node.js Program with a different Port for example: 1000. It works!.
live-serve --port=8090
simple and easy
I had the same problem.
What I did was I changed the port of the default website in the IIS-Manager from 8080 to 80 and than I reseted the IIS-Manager. It worked!
live-server --port=8090
simple and easy
Just run
serve --port=80
where 80 is the port you want to launch the program.

Is supertest compatible with express.js 2.5.8?

I am using express.js version 2.5.8 (from legacy code) and am looking to test route loading using supertest. I am having an issue with the server running, but not stopping. I run my tests using jasmine-node, which indicates that my assertion succeeds. However, the console shows that the process is still running.
var request = require('supertest')
, express = require('express');
describe('Example Test', function() {
var app;
beforeEach(function() {
app = express.createServer();
app.configure(function() {
app.set('port', process.env.PORT || 3000);
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
});
app.get('/', function(req, res){
res.send(200);
});
});
it('index should return 200', function(done) {
request(app)
.get('/')
.expect(200)
.end(function(err, res) {
expect(err).toBe(null);
done();
});
});
});
This example is adapted from one likely using express.js 3.x.x. My assumption is that the express server behaves differently, leading to it not closing when the request terminates inside the test. I am uncertain how to correct this issue.
The server is still running because you aren't closing it anywhere. Just add app.close() to your end(function(){}) to stop the express server. If you also want to exit from node use process.exit().