I installed nodejs and used npm init then i used npm install express --save. I have made my own app.js to define webserver and make it running on my localhost. Now i get error: Cannot GET/. Bellow is app.js code:
var express = require('express');
var app = express();
//here we add content to webpage .get or .post
app.get('/', function (req, res) {
res.send('Hello World!');
});
//here we setup port
app.listen(1337, function(){
console.log('port 1337');
});
Related
When I run my app locally it works just fine. I deployed my app on Heroku and the build was successful without any errors. However, whenever I open the app, I just get the revolving React icon page that you get when you first create a react app. I'm getting nothing in the console and the Heroku log is giving me back status 200 so I'm not sure what's going on.
I notice it has something to do with my build folder because when I delete the app returns "Not Found".
I believe its in my server.js file.
require("dotenv").config();
const express = require('express');
const port = process.env.PORT || 8080;
const path = require("path");
var app = express();
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
if (process.env.NODE_ENV === "production") {
app.use(express.static("client/build"));
}
if(process.env.NODE_ENV === "production"){
app.use("*", function(req, res){
res.sendFile(path.join(__dirname, "/client/build/index.html"));
})
}
app.listen(port, (req, res) => {
console.log(`server listening on localhost:${port}`);
});
I just tried copying over from an app that I did successfully launch on heroku. I'm fairly new to coding so I don't even know what half of it means. If someone could help me out, that would be greatly appreciated.
That's probably because you are using create-react-app and you're not serving the /build folder. You can easily add an express server to do it.
First, install the express module:
npm install express --save
And the add a server.js file that will serve your /build/index.html on all requests:
const path = require('path');
const express = require('express');
const app = express();
const port = process.env.PORT || 3000;
app.use(express.static(path.join(__dirname, 'build')));
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'build/index.html'));
});
app.listen(port, () => {
console.log(`The server is running at http://localhost:${port}`);
});
I figured it out. I didnt have a build script in my package.json
I have the following code in node.js which is very basic express code but I can't get it to work. when I visit localhost/, it gives me text "Cannot GET /". It should display Hello world.
const express = require('express');
const app = express();
app.get('/', function (req, res) {
res.send('Hello World!')
});
do you open port?
The server must open the port.
app.js
var express = require('express');
var app = express();
app.get('/', function(req, res) {
res.send("Hello World");
});
app.listen(3000, function() {
console.log("server open");
});
If listen method called by app, Prepares to receive the client's response to the port passed as the first argument.
U can execute this code.
node app.js OR supervisor app.js OR forever start app.js ETC
I using the port 4200 in my angular, and port 3000 for my nodejs, when i am running angular the nodejs does not work. Connection refused problem occurred.
What i do? Plz answer my question
That's not how it supposed to work.
Running Angular on 4200 port is the CLI's ability for live reload & All, it doesn't create the distribution folder or the dist.
This is how it should work
you create the dist folder [Html,CSS,JS]
You write an express code in Node JS to serve the dist directory or index.html
You copy the dist to the public accessible folder in node JS
When you hit localhost:3000 then & Only then Node JS as well as Angular will run.
Example :
create 1 folder server
In it write app.js with this code.
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
app.use(logger('dev
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(__dirname));
app.get('/*', function (req, res) {
res.sendFile(path.join(__dirname,'index.html
});
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
if (app.get('env== 'development')
{
app.listen(3000, function () {
console.log('Example listening on port 3000!');
});
}
else{
app.listen(8080, function () {
console.log('Example listening on port 8080!');
});
}
module.exports = app;
This snippet assumes that u have installed cookie-parser body-parser morgan.
So basically any request redirects to index.html which is the starting point of the Angular 2 App.
Now when u do
node app.js
your angular app will be served through Node JS & Express
I'm building a web app using Angular2, to create the project I'm using Angular2 CLI webpack. Angular2 app uses other external packages also (Eg: Firebase). In addition to that, I need to create a REST API running on node.js
How can I serve both of Angular2 app and REST API using node.js server
Use ng build to build your app into build directory.
Create nodejs app to server the build directory as static content, then create route for api.
Following is an example of nodejs app using express that will serve the Angular2 app:
/*
Put content of angular2 build into 'public' folder.
*/
const html = __dirname + '/public';
const port = 4000;
const apiUrl = '/api';
// Express
const bodyParser = require('body-parser');
const compression = require('compression');
const express = require('express');
var app = express();
app
.use(compression())
.use(bodyParser.json())
// Static content
.use(express.static(html))
// Default route
.use(function(req, res) {
res.sendFile(html + 'index.html');
})
// Start server
.listen(port, function () {
console.log('Port: ' + port);
console.log('Html: ' + html);
});
// continue with api code below ...
None of the answers worked properly for me. And if it worked, the Angular routing did not work on reload.
So this is how I solved it. Angular routing works even on full page reload.
function getRoot(request, response) {
response.sendFile(path.resolve('./public/angular/index.html'));
}
function getUndefined(request, response) {
response.sendFile(path.resolve('./public/angular/index.html'));
}
// Note the dot at the beginning of the path
app.use(express.static('./public/angular'));
app.get('/', getRoot);
app.get('/*', getUndefined);
NO angular base-href rewrite is required! Just use ng build or ng build --prod.
Here is full back end code which is working
const express = require('express');
var app = express();
var port = 9999;
function getRoot(request, response) {
response.sendFile(path.resolve('./public/angular/index.html'));
}
function getUndefined(request, response) {
response.sendFile(path.resolve('./public/angular/index.html'));
}
app.use(express.static('./public/angular'));
app.get('/', getRoot);
app.get('/*', getUndefined);
// Start server
app.listen(port, function () {
console.log('server running at port: ' + port);
});
Based on #NTN-JAVA answer, here's a solution to serve an Angular app from NodeJS server.
Here's the summary from beginning:
npm install -g #angular/cli
ng new PROJECT_NAME
cd PROJECT_NAME
npm install nodemon express cookie-parser body-parser morgan method-override --save
5.Create app.js:
var express = require('express');
var app = express();
var morgan = require('morgan');
var bodyParser = require('body-parser');
var port = process.env.PORT || 3000;
var methodOverride = require('method-override'); // simulate DELETE and PUT (express4)
var router = express.Router();
console.log('——————————- Run on port '+ port);
/****************************** Router ***************************/
router.get('*', function(req, res){
res.sendFile('index.html', { root: __dirname + '/' });
});
/****************************** /Router ***************************/
//app.use(morgan('dev')); // log every request to the console
app.use(express.static(__dirname + '/')); // Static (public) folder
app.use(bodyParser.urlencoded({extended:true}));// get information from html forms
app.use(bodyParser.json());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
app.use(methodOverride());
app.use('/', router); // app.use('/parent', router); call all from localhost:port/parent/*
app.listen(port);
Edit package.json file:
{
...
"scripts": {
"start": "ng build; cp app.js dist/app.js; node dist/app.js",
}
...
}
Run npm start
This answer also offers a solution for calling direct URLs from browser and resolving them correctly in your app.
Follow the Express node server with Angular 2 CLI document to serve your application through Node.js server. The application is being served Through Node.js and a REST full API. You can design this REST as your requirements.
E.g.
Serve application with http://localhost:5000/app
app.get('/app/*', function(req, res) {
res.sendFile(path.join(__dirname, 'index.html'))
});
or
Serve data from REST calls with http://localhost:5000/rest/contacts
app.get('/rest/user', function(req, res) {
res.send({
"id": 2,
"name": "Jhon",
})
});
Step 1: In order to get static content, run this command in your angular app directory -
ng build --prod
Step 2: The first step will create a dist folder in your current directory, move all files in the dist folder to public folder of your node app -
Step 3: Create a node server. App.js -
var path = require('path');
var express = require('express');
var cookieParser = require('cookie-parser');
var cookieParser = require('cookie-parser');
const allowedExt = [
'.js',
'.ico',
'.css',
'.png',
'.jpg',
'.woff2',
'.woff',
'.ttf',
'.svg',
];
var app = express();
app.use(cookieParser());
function getAngularApp(request, response) {
response.sendFile(path.resolve('./public/index.html'));
}
function defaultHandler(request, response) {
if (allowedExt.filter(ext => req.url.indexOf(ext) > 0).length > 0) {
response.sendFile(path.resolve(`public/${req.url}`));
} else {
response.sendFile(path.resolve('./public/index.html'));
}
}
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', getAngularApp);
app.get('/*', defaultHandler);
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
var express = require('express'),
app = express.createServer();
app.use(express.logger());
app.get('/', function(req, res){
res.send('Hello World');
});
app.listen();
console.log('Express server started on port %s', app.address().port);
I get the error "unexpected identifier"
what is wrong with the code?
I don't think there's a method createServer in express. This is from their docs:
var express = require('express');
var app = express();
app.get('/', function(req, res){
res.send('hello world');
});
app.listen(3000);
http://expressjs.com/en/starter/hello-world.html
express.createServer() has been deprecated. Please check this question
Nodejs / Express - Launching my app: express.createServer() is deprecated
on how to update the project to work with more recent versions of express.
You didn't declare port anywhere and also you didn't mention the port number also.When you are using app.address().portit does not hold any port value so that's why it returns undefined.Here is my code hope this helps for you.Just save this code with a name I saved it as server.js
var http=require('http');
var express = require('express');
var app = express();
app.set('port', process.env.PORT || 8000);
app.get('/', function(req, res){
res.send('Hello World');
});
var server = http.createServer(app);
server.listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
OUTPUT IN TERMINAL:
C:\Users\nodejs\tasks>node server.js
Express server listening on port 8000
Open a browser and type localhost:8000 then
OUTPUT IN BROWSER:
Hello World