I have a Node.js app that uses Express.js to listen for connections. The code is something like so:
const express = require("express");
var server = express();
server.get("/test", (req, res) => testResponse(req, res));
server.listen(9001);
console.info("Server is listening to port 9001.");
I'd like to implement a way to restart the server without having to restart the whole app. However, I can't seem to properly shut down the server and free the port.
Here's what I tried:
server.close();
console.info("Server closed. Restarting.");
var server = express();
server.get("/test", (req, res) => testResponse(req, res));
server.listen(9001);
console.info("Server is listening to port 9001.");
As soon as I run this, I get
Error: listen EADDRINUSE :::9001
What would be the correct way to do this?
Cheers.
server.close() is asynchronous and takes a callback. Try waiting until the server is actually closed before starting a new one:
server.close(()=>{
console.info("Server closed. Restarting.");
var server = express();
server.get("/test", (req, res) => testResponse(req, res));
server.listen(9001);
console.info("Server is listening to port 9001.");
});
As of Express 3, the app.close() method seems to have disappeared, which means Express users have no means of gracefully stopping an application. Express is really a listener to http request events which means you can do this:
const express = require("express");
var server = express();
server.get("/test", (req, res) => testResponse(req, res));
var app = server.listen(9001, function () {
console.log('Listening :)');
app.close(function () {
console.info("Server closed. Restarting.");
var server = express();
server.get("/test", (req, res) => testResponse(req, res));
server.listen(9001);
console.info("Server is listening to port 9001.");
});
});;
console.info("Server is listening to port 9001.");
For more on this you can refer hardening nodejs for production
Related
I'm using AWS with Nodejs and express. The server runs on an ec2 instance with alb. My website tries to connect to another website where the server runs, that's e. g. server.com. When I try to get on the server.com, it shows me the text it should, but if I go on server.com/create-checkout-session, it gives me a 502 Bad Gateway. My website that tries to connect gives out a CORS preflight request error in the console because no "Access-Control-Allow-Origin" header would be present on the requested source. I tried a lot, nothing worked that's why I'm asking.
Here the server.js:
const express = require('express');
const cors = require('cors');
require('dotenv').config({ path: './.env' });
const createCheckoutSession = require('./api//checkout');
const webhook = require('./api/webhook');
const app = express();
const port = 8080;
app.use(express.json({
verify: (req, res, buffer) => req['rawBody'] = buffer,
}));
app.use(cors({ origin: true }));
app.get('/', (req, res) => res.send('hello world'));
app.post('/create-checkout-session', createCheckoutSession);
app.post('/webhook', webhook);
app.listen(port, () => console.log('server listening on port', port));
I have a completed script that acts as a parser. The script is written in NodeJS and it works properly. The script returns an array of data and also saves it to my computer.
I would like to run this script from the frontend, at the click of a button. As far as I understand, I have to send a request to the server? It's suggested to use Express for the server, but I still haven't figured out how to call a third-party script from it, much less return any data from it.
Right now all I want is for my script to run when I make a request for the root directory "/" and send me a json in response (or for example a json file)
const express = require('express')
const runParser = require("./parser");
const app = express()
const port = 3000
app.get('/', async (req, res,next) => {
await runParser()
next()
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
All you need for Express is this:
const express = require('express');
const app = express();
const runParser = require("./parser");
const port = 3000;
app.get("/", (req, res) => {
runParser().then(results => {
res.json(results);
}).catch(err => {
console.log(err);
res.status(500).send("error");
});
});
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
And, then you can access that either by just going to:
http://localhost:3000
from your local host or
http://yourdomain.com:3000
in the browser or by issuing an ajax call to the desired URL from webpage Javascript.
I wouldn't personally put this type of activity on a GET request to / because that can be hit by things like web crawlers, search engines, etc...
It probably belongs on a POST (so crawlers won't issue it) and I'd personally put it on some pathname such as:
app.post("/runparser", (req, res) => {
// put your code here
});
And, then use a form submission or ajax call to that URL to trigger it.
I'm trying to learn nodejs and express and i created a simple server. I want to run some JS code for response.
When I used this method it's works.
const express = require('express');
const path = require('path');
require('dotenv').config();
const app = express();
const port = process.env.PORT || "8000";
app.get('/', (req, res) => {
res.send(`<script>
console.log("Program works!");
</script>`);
});
app.listen(port, () => {
console.log(`Listening to requests on http://localhost:${port}`);
});
But writing JS as String is hard so I tried this:
const express = require('express');
const path = require('path');
require('dotenv').config();
const app = express();
const port = process.env.PORT || "8000";
app.get('/', (req, res) => {
res.send(`<script src="./response.js"></script>`);
});
app.listen(port, () => {
console.log(`Listening to requests on http://localhost:${port}`);
});
And i get this error:
GET http://localhost:8000/response.js net::ERR_ABORTED 404 (Not Found)
When you send this:
<script src="./response.js"></script>
to the browser, the browser will parse that and see the src attribute and will then immediately request ./response.js from your server. But your server doesn't have any route to respond to that request (thus it gets a 404 error back from your server). Remember that a nodejs server serves NO files by default (unlike some other web servers). So, you have to create routes or middleware for anything that you want it to serve.
So, you need to add a route to your server that will response to a request for response.js. First change your <script> tag to this:
<script src="/response.js"></script>
You want the request to be "path absolute" so it does not depend upon the path of the containing page. Then, you need to add a route handler for response.js to your server.
This can be done as a single route:
app.get('/response.js', (req, res) => {
res.sendFile("response.js", {root: __dirname});
});
Or, you can use express.static() to serve a whole directory of publicly available files with one line of code (if you also move all publicly available static files to their own directory away from your server files).
I am trying to upload my nodejs work on googlecloud functions but i am getting timeout error in logs. I am trying to load the homepage using templates. I am unable to use the helloworld function properly. Below is a part of the code and not a complete code.
exports.helloworld = ()=>{
app.get('/',(req, res)=> {
res.render('home');
});
}
app.listen(3000, () => {
console.log('app now listening for requests on port 3000');
});
If you want to use express js routing in the cloud functions, you need to export the express js app instead of running the server.
index.js
const express = require('express');
const app = express();
app.get('/',(req, res)=> {
res.render('home');
});
app.get('/login',(req, res)=> {
res.render('login');
});
exports.helloworld = app;
Server is starting without any errors but the URL is hit its showing no application running.
URL:link_To_Server
My Code:
var express= require('express');
var app=express();
app.get('/', function(req, res, next) {
console.log('home');
res.send(200);
res.end('getting requests');
});
console.log('server started');
You didn't actually set the server to listen to a port. Replace
console.log('server started');
With
app.listen(3000, function() {
console.log('server started');
});
Note that with the above example, the bound port is 3000. For more info, see the API doc