0

I am new angular, trying to set up new project in angular, using angular/cli. I did following steps to setup a express server and angular as the front end.

installed angular/cli; then ng new testApp; ng build; this created a dist folder like dist>testApp>and all the files(index,html, main.js. . . . so on),

and i have installed express and body-parser. now in my server.js i have following code.

const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const http = require('http');
const app = express();


app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended : false}));


app.use(express.static(path.join(__dirname, 'dist')));

app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname, 'dist/testApp/index.html'));
});

const port = process.env.port || '3000';
app.set('port', port);

const server = http.createServer(app);

server.listen(port, () => console.log(`listening on port : ${port}`));

Now when i started the server and tried "http://localhost:3000/" on my browser I see errors in console saying unexpected token in all .js files like main.js, polyfills.js so when i look at the sources tab i can see even the js files are having the same index.html content in them.

So can any tell me what i was missing or doing the wrong way. please. Thanks.

1
  • In your server.js all get requests are pointing to index.html, thats why you are getting all files with index.html contents. See my answer below. Commented Jun 21, 2018 at 10:00

1 Answer 1

0

Just rewrite your server.js file as below.

const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const http = require('http');
const app = express();


app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended : false}));


app.use('/', express.static(path.join(__dirname, 'dist', 'testApp')));


const port = process.env.port || '3000';
app.set('port', port);

const server = http.createServer(app);

server.listen(port, () => console.log(`listening on port : ${port}`));

This may solve your issue.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks for the reply. it solved my issue. but when i use app.get('/', (req, res) => { res.sendFile(path.join(__dirname, 'dist', 'testApp')); }); it gives me "can not Get" , so shouldn't i be using res.send file or is it some thing else that i am doing?
You need not use app.get for showing the angular site. app.get or app.post can be used for API calls which your angular site needs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.