从angular客户端发送到后端restapi的post请求有问题。要清楚的是,当我从 Postman 发送相同的要求,它是正确的工作!其他get请求甚至授权后jwt请求都能正常工作。我的restapicontroller post方法:
@RequestMapping(method=RequestMethod.POST,value="/cryptocurrency/{name}")
@PreAuthorize("hasRole('USER')")
@ResponseBody
public ResponseEntity addCryptocurrencyToUserFavouriteList(@PathVariable String name){
logger.info("Calling /api/cryptocurrency/"+name+" POST method",CryptocurrencyController.class);
try{
String username=SecurityContextHolder.getContext().getAuthentication().getName();
userService.addCryptocurrencyToFavourite(username,name);
return new ResponseEntity(HttpStatus.OK);
}catch(Exception e){
logger.error("Server Error "+ e, CryptocurrencyController.class);
return new ResponseEntity(HttpStatus.valueOf(404));
}
}
angular rest api服务:
httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
constructor(private http: HttpClient) { }
public addCryptocurrencytoUserFavouriteList(cryptocurrencyname: string):Observable<any>{
return this.http.post(this.apiURL+"/cryptocurrency/"+cryptocurrencyname,this.httpOptions);
}
方法是从组件调用的,只是什么都没有发生,后端前端也没有。我还有一个authiterceptor在angular端,它可以正确地与其他方法一起工作。身份验证侦听器:
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
TOKEN_HEADER_KEY = 'Authorization';
constructor(private token: TokenStorageService) { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let authReq = req;
const token = this.token.getToken();
if (token != null) {
authReq = req.clone({headers: req.headers.set(this.TOKEN_HEADER_KEY, 'Bearer ' + token)});
}
return next.handle(authReq);
}
}
所以在我看来,问题可能在服务器端的post方法中,在我获取securitycontext的那一刻,但在那条指令之前,我有一个记录器信息,它没有显示在服务器输出中,所以idk我还能做什么。有什么想法吗?谢谢你的帮助!
暂无答案!
目前还没有任何答案,快来回答吧!