I am new in Angular
. I tried to create a CRUD operation using Nodejs
and Angular
. I am using Nodejs
and Express
for backed and Angular
for frontend.
When I navigate on page using routerLink its work fine, but when I navigate on the page and then I refresh the page it shows a page not found error.
I know what happened there, the route is not defined in the Express app so I refresh the page it shows the 404 error.
How do I make this work with Angular and Express routes?
Here is my code.
app.js
( Server )
const express = require('express');
const path = require('path');
const http = require('http');
const bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({extended : false}));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname,'dist/MEAN-blog')));
app.get('/',(req,res) =>{
res.sendFile(path.join(__dirname,'dist/MEAN-blog/index.html'));
});
app.post('/register',(req,res) =>{
var u = new User(req.body);
u.save();
res.send(u).status(200);
})
var server = http.createServer(app);
server.listen(8080,'0.0.0.0',() =>{
console.log('Server is running on 8080');
})
Here is the routes of angular
const routes: Routes = [
{
path : '',
component : PostsComponent
},
{
path : 'users',
component : UsersComponent
},
{
path : 'users/:id',
component : UsersComponent
},
{
path : 'post/:id',
component : PostDetailsComponent
},
{
path : 'login',
component : LoginComponent
},
{
path : 'signup',
component : SignupComponent
},
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
I am using angular 5
how can i solve this issue ?
Thanks
Usually what I do is include all my api endpoints first, and then at the end add this
app.get('*',(req,res) =>{
res.sendFile(path.join(__dirname,'dist/MEAN-blog/index.html'));
});
This way any endpoint that isn't /api
will return index.html and angular routing will take over from there.
Another alternative is using SSR but its kind of a pain.