how to run angular 6 app with nodejs api on production?

可紊 提交于 2019-12-24 03:37:45

问题


Hi I am new to angular6

In development mode I have worked in angular 4200 port and node in different port (8080) in my operations. but now I want to move my app into production mode. for that I had build my angular project by using ng build command. after i get a dist folder is created on the root folder.

so i went to server.js file here I had add my static file

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

app.use('/',(req,res)=>{

    res.sendFile(path.join(__dirname,'dist/MDProject/index.html'))
});

click here to read my server.js file

by this when ever I redirect to my local host it is opening but in server.js side i didn't get any response.

when ever I try to login I am getting this error.

can anyone help me to solve this


回答1:


I think there are 2 things wrong here in your code.

First, update your code

From:-

app.use('/',(req,res)=>{

    res.sendFile(path.join(__dirname,'dist/MDProject/index.html'))
});    

To:- This code needs to be added just before your app.listen(app.get('port')) code

app.get('*', function(req, res) {
     res.sendfile('./public/MDProject/index.html'); 
     // load the single view file (angular will handle the page changes on the front-end)
});

Second, Serve your file from your public folder(In your case I think it is the dist folder). So update your code like this.

app.use(express.static(__dirname + '/dist/MDProject'));



回答2:


after I removed this line in my server.js file

app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');

and I paste this line before port creation.

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

app.use('/',(req,res)=>{

    res.sendFile(path.join(__dirname,'dist/MDProject/index.html'))
});

now it is working fine.




回答3:


Use this to go to index page.

app.get('*', (req, res) => {
 res.sendfile('./public/MDProject/index.html');
})

with that you have to make folder in public in node

app.use('/', express.static('/dist/MDProject'))

Then in your app dist folder -> index.html

<base href="http://192.168.1.1:3000/admin-panel/">

This is my working code. Let me know if you have still any issue. :)



来源:https://stackoverflow.com/questions/53099973/how-to-run-angular-6-app-with-nodejs-api-on-production

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!