我有一个 Angular 4 客户端服务,它调用在带有 Postmapping 注释的 Java 服务器上声明的 rest 方法。
当我从 Angular 调用它时,服务器不接受它。但是当我只添加 header Content-Type application/json 时,在 postman 上尝试它会起作用。
添加了相同的 header ,甚至添加了一些其他 header ,从 Angular 来看它仍然不起作用。
这里是 Angular 服务的代码:
public login(username: string, password: string): Observable<{}> {
const requestParam = {
username: username,
password: password,
email: 'email@at.pt'
};
const options = this.generateOptions();
const body = JSON.stringify(requestParam);
return this.http
.post(AuthService.SIGNIN_URL, body, options)
.map(this.extractData)
.catch(this.handleError);
}
我现在的标题:
const headers = new Headers({
'Access-Control-Allow-Origin' : '*',
'Access-Control-Allow-Methods': 'GET, POST, PATCH, PUT,
DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Origin, Content-Type, X-
Auth-Token',
'Content-Type': 'application/json'
});
以及浏览器上的给定错误:
2zone.js:2744 OPTIONS
http://localhost:8080/api/auth/login net::ERR_ABORTED
invokeTask @ zone.js:1427 globalZoneAwareCallback @
zone.js:1445 login?returnUrl=%2F:1 Failed to load
http://localhost:8080/api/auth/login: Response to
preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the
requested resource. Origin 'http://localhost:4200' is
therefore not allowed access. The response had HTTP
status code 403. auth.service.ts:205 Server error
服务端使用spring-boot:
导入org.springframework.web.bind.annotation.PostMapping;
导入org.springframework.web.bind.annotation.RequestBody;
导入org.springframework.web.bind.annotation.RestController;
/**
* Returns authentication token for given user
*
* @param authenticationRequest
* with username and password
* @return generated JWT
* @throws AuthenticationException
*/
@PostMapping(LOGIN_URL)
public ResponseEntity getAuthenticationToken(@RequestBody JwtAuthenticationRequest authenticationRequest)
throws AuthenticationException {
System.out.println("on login server side");
...
}
public class JwtAuthenticationRequest implements Serializable {
private String username;
private String email;
private String password;
...
}
谢谢!
最佳答案
你应该在服务器端创建它:
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
}
在你的方法之上,你还应该像这样添加 @CrossOrigin
:
@CrossOrigin
@PostMapping(LOGIN_URL)
public ResponseEntity getAuthenticationToken(@RequestBody JwtAuthenticationRequest authenticationRequest)
throws AuthenticationException {
System.out.println("on login server side");
...
}
关于java - 通过 angular 4 http post 连接到服务器端不允许的 java rest api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46484705/