I'm reading from a few other similar questions/answers and one point seems to be that any valid JS is basically TS as well?
If that is the case:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server started on port ${port}`));
TS attempt
import express = require('express');
import bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
const port: number;
port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server started on port ${port}`));
import express from "express";
import bodyParser from "body-parser";
import path from "path";
import config from "config";
const app = express();
app.use(bodyParser.json());
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server started on port ${port}`));
Although the above code can still be considered "valid javascript" i would say that is the idiomatic typescript way of writing the code snippet you posted. This is because typescript makes any module imported with require syntax of type any where-as import will always try and look for type definitions and complain if they're not there.
When working with Express/NodeJS/Typescript i would always suggest starting with this demo app as it is a really good boiler plate for getting started with those technologies and is maintained by microsoft.
https://github.com/microsoft/TypeScript-Node-Starter
Related
I am trying to build my first app. It's a calculator that measures the level of caffeine in your blood.
I copied the code from : https://expressjs.com/en/starter/hello-world.html (copied below), but it is not showing a page with the words "Hello World!".
Instead, I see 2 links to my 2 files within my folder "CaffeineCalc" (calculator.js + json file). I have copied below the page it shows me. [what my browser page shows instead of Hello World][1]
const express = require('express');
const app = express();
const port = 5500;
app.get('/', (req, res) => {
res.send('Hello World!')
});
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
});
Let me know if you understand what I am doing wrong. Thanks!
[1]: https://i.stack.imgur.com/L6bnv.png
From The Picture you provide, it looks like a live-server running and not your NODE application
So To Fix That You Need to open the path of that dir in any terminal or command prompt and run
$ npm install
cause I can't see any node_module folder
then
$ node index.js
to start the node server
You can now open Your Browser to
http://localhost:5000
you need to use express urlencoded.
const express = require('express');
const {
urlencoded
} = require('express');
const app = express();
const PORT = process.env.PORT || 4000;
app.use(express.json())
app.use(urlencoded({
extended: true
}))
app.listen(PORT, () => {
console.log(`Example app listening at http://localhost:${PORT}`)
})
Following is my code -
apps.js
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
app.get('/api/users', (_req, res) => {
res.send('Hello World');
})
app.listen(PORT, () => {
console.log(`Server running on port: `, PORT);
});
.env file
PORT=8000
Now when I run the program though terminal via command - node app.js
I am getting -
Server running on port: 3000
but I want it to run on 8000 and pick it from .env file. Let me know what I am doing wrong here.
I know while running from terminal I can define PORT=8000 or app.set() but I am looking to pick it from an environment file. Let me know what I am doing wrong here / in terms of understanding.
You can use dotenv npm package for custom environment variables.
Usage
Create a .env file in the root of your project:
PORT=8000
As early as possible in your application, import and configure dotenv:
require('dotenv').config();
// Your .env variables is now available in process.env object
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
app.get('/api/users', (_req, res) => {
res.send('Hello World');
})
app.listen(PORT, () => {
console.log(`Server running on port: `, PORT);
});
Read more in the official package: dotenv
I have a nodejs server running the common framework express. I have noticed recently that when I make requests from my server, I get this error at seemingly random times, for example, if I were to make a request twice, the error would usually only happen the first request, and not the second. I'm having trouble pinpointing what is causing this error, because I often write my code in one go, then test it later. Here is the error in full:
TypeError: Cannot read property 'app' of undefined
at json (/home/user/Desktop/project/node_modules/express/lib/response.js:256:18)
at process._tickCallback (internal/process/next_tick.js:68:7) 'Unhandled Rejection at Promise' Promise {
<rejected> TypeError: Cannot read property 'app' of undefined
at json (/home/user/Desktop/project/node_modules/express/lib/response.js:256:18)
at process._tickCallback (internal/process/next_tick.js:68:7) }
All that I can tell from this error is that it may involve some reference to "app", however I am not sure what it could be specifically, as I haven't changed anything pertaining to "app" in express recently. Here is my express configuration on my server file:
const express = require('express'),
user = require('./routers/User.js'),
helmet = require('helmet'),
app = express();
app.use(helmet());
app.use(cors());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());
app.set('trust proxy', true);
//map router files to respective urls
//these are stored in a directory and set above, these contain all of the handlers for each of my routes
app.use('/user', user);
//set port and listen on it
app.listen(5000, () => console.log("Server running on port 5000"));
If anything else is needed of me, please ask. I've tried to include every reference pertaining to the word "app" in my code, but that may not be enough.
EDIT: I thank you all for trying to help, but the code I provided was not intended to work, it was simply an example of what I import, this is an error with express, and I'm just trying to find out what kind of behavior would cause it. Sorry for the confusion.
You are most likely missing a comma after "helmet = require('helmet')
const express = require('express'),
user = require('./routers/User.js'),
helmet = require('helmet'),
app = express();
app.use(helmet());
app.use(cors());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());
app.set('trust proxy', true);
//map router files to respective urls
//these are stored in a directory and set above, these contain all of the handlers for each of my routes
app.use('/user', user);
//set port and listen on it
app.listen(5000, () => console.log("Server running on port 5000"));
for your code to work you have to add
const express = require('express'),
user = require('./routers/User.js'),
helmet = require('helmet')
----> const app = express();
or helmet = require('helmet'), <-----
app = express()
//Worked fine for me. removed ur local import. This runs fine.
const express = require('express');
const helmet = require('helmet');
const cors = require('cors');
const bodyParser = require('body-parser')
app = express();
app.use(helmet());
app.use(cors());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());
app.set('trust proxy', true);
//set port and listen on it
app.listen(5000, () => console.log("Server running on port 5000"));
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
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I'm building a web app with Node.js, Express framework, and EJS templates.
Here's my server:
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
app.set('view engine', 'ejs');
app.get('/', (req,res) => {
res.render('home', {
headline : 'We are always on a mission for Clearn Benglauru'
});
});
app.use(express.static(__dirname, '/public'));
app.listen(PORT, () => {
console.log(`The app is running on port : ${PORT}`);
});
After starting the server, I got this error:
TypeError: Object prototype may only be an Object or null: /public
at Function.create (<anonymous>)
at Function.serveStatic [as static] (<DIRECTORY>\node_modules\serve-static\index.js:48:21)
at Object.<anonymous> (<DIRECTORY>\test:12:23)
Maybe related to Node.JS object prototype may only be an Object or null with Redis
Use the module path to serve your public folder.
const express = require('express');
const app = express();
const path = require('path');
const PORT = process.env.PORT || 3000;
app.set('view engine', 'ejs');
app.get('/', (req,res) => {
res.status(200).send('Ok!');
});
app.use(express.static(path.join(__dirname, 'public')));
app.listen(PORT, () => {
console.log(`The app is running on port : ${PORT}`);
});
I didn't have EJS or an EJS view file, so I replaced the res.render line with a res.status().send() for the example. Tested and works.