当我从angular 2应用程序发送http post请求时,我收到403禁止错误。下面是form.component.ts和service.ts的代码。
form.component.ts
`import {Component, OnInit} from '@angular/core';
import { RegisterUser} from '../Model/RegisterUser';
import { RegisterService } from
'../Services/RegisterService';
@Component({
selector:'register-user-form',
templateUrl:'/app/Htmls/Register.html',
providers : [RegisterService]
})
export class RegisterUserComponent implements OnInit{
submitted=false;
constructor(private registerUserService : RegisterService ){
}
ngOnInit(){
}
onSubmit(value:RegisterUser){
this.registerUserService.pushUser(value).subscribe(
);
console.log(value) ;
}
}`
以下是service.ts
import { Injectable } from '@angular/core';
import { Headers,Http, Response } from '@angular/http';
import { RegisterUser} from '../Model/RegisterUser';
import 'rxjs/add/operator/map';
@Injectable()
export class RegisterService {
private headers = new Headers({'content-type': 'application/json'});
constructor(private _http : Http){}
pushUser(registerUser:RegisterUser){
console.log("submittin user "+JSON.stringify(registerUser));
const url:string="http://localhost:8080/register/saveUser";
return this._http.post(url,JSON.stringify(registerUser),
{headers:this.headers}).
map((response:Response) => response.json());
}
}
请帮忙!
答案 0 :(得分:6)
也许你错过了Spring控制器中的@CrossOrigin注释,以允许来自不同来源的请求,例如你从Angular应用程序发送的请求
它适用于邮递员,因为您发送的申请来自与春季申请相同的来源
示例:spring server localhost:3000,angular server localhost:8080,那么没有@crossOrigin你就无法访问3000但你可以直接从邮递员访问3000