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;
Related
iam new in node.js .iam faceing this problem .When i use express and use ''use'' request to get response to the chorome but this erro came in my chorme bowser Cannot GET.
or my app.js file or index.js is in one same folder . folder name is static. Iam not good in english please help me. Or if i use nodemon togther than when i get to localhost the the loaclhost cannot and show this 'This site can’t be reached'
i dont know how to fix it can any help me to fix this problem this the code
const express = require("express");
const app = express();
const port = 8080;
app.use('/static',express.static('express/static'));
app.get("/", (req, res)=>{
res.status(200).send("This is the first page of node express");
});
app.get("/about", (req, res)=>{
res.send("This is the about page of node express");
});
app.post("/postabout", (req, res)=>{
res.send("This is the postabout page of node express");
});
app.post("/erro", (req, res)=>{
res.status(404).send("This page has been errored in code of 404");
});
app.listen(80,'127.0.0.1', () =>{
console.log(`The application started and the port is ${port}`);
});
This the image of my code and chrome
In app.listen you passed wrong port means you intialized port as 8080 but passed 80
app.listen(8080,() =>{
console.log(`The application started and the port is ${port}`);
});
Basically, app.use function uses a middleware when a particular API is called it does not a get request.
So try app.get instead of app.use it will work.
app.get('/static', (req, res) => {
// Do your stuffs.
return res.send(response)
})
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).
For some reason my express router is not processing requests correctly. My router module is in the same directory as the app entry point. The app is located in index.js:
const express = require('express')
const app = express()
// loading router
const mainRouter = require('./mainRoutes.js')
// mounting router
app.use('/', mainRouter)
app.listen(3000)
console.log('Express server running on port 3000')
The router module is located in mainRoutes.js:
const path = require('path')
const express = require('express')
const mainRouter = express.Router()
mainRouter.get('/', function (req, res) {
res.send('Hello World, I\'m Node.js')
})
mainRouter.get('/about', function (req, res) {
res.sendFile(path.join(__dirname, 'views', 'about.html'))
})
module.exports = mainRouter
When I launch the server locally with live-server and make the following example request in chrome browser:
http://127.0.0.1:8080/about
I get the following error response:
Cannot GET /about
Does anyone have any idea as to what the issue is?
The server is listening on port 3000: app.listen(3000)
But you're trying to access it from port 8080: http://127.0.0.1:8080/about
Try http://127.0.0.1:3000/about
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