Angular 5 POST requests for my page

2019-09-16 11:54发布

问题:

I'm receiving POST request to my Angular page, which might look like:

https://www.myangularsite.com/login 
"POST /login HTTP/1.1
token: randomstring"

My app module looks like

export const routes: Routes = [
  { path: 'login', component: LoginComponent },
  { path: '', redirectTo: 'login', pathMatch: 'full' },
  { path: '**', redirectTo: 'login', pathMatch: 'full' }
];

@NgModule({
  declarations: [
    LoginComponent,
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    RouterModule.forRoot(routes, {errorHandler: errorLogger } )
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }

My problem is that Angular application doesn't accept POST method requests, only GET. Page displays

Cannot POST /login

I'm running web server through ng serve. Is it possible to set it up to listen to POST requests? I can't change received request to GET.

Even though it is POST request, it is not a backend call. It is called after authorization (similar from oauth), therefore it should display page after login.

回答1:

You can use node.js Express as your CLI server. Please see the post at  http://tattoocoder.com/angular2-giving-your-cli-server/  on how to do that.

Then in your express server.js, you can listen the post request for login:

var express        =         require("express");
var bodyParser     =         require("body-parser");
var app            =         express();

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

app.get('/',function(req,res){
  res.sendfile("index.html");
});
app.post('/login',function(req,res){
  var user_name=req.body.user;
  var password=req.body.password;
  console.log("User name = "+user_name+", password is "+password);
  res.end("yes");
});
app.listen(3000,function(){
  console.log("Started on PORT 3000");
})