【发布时间】:2016-11-27 19:42:02
【问题描述】:
我在 Angular 2 中有一个简单的应用程序。我创建了 http.service.ts:
import {Injectable} from 'angular2/core';
import {Http} from 'angular2/http';
import {Observable} from "rxjs/Observable";
import 'rxjs/Rx';
import {Headers} from "angular2/http";
@Injectable()
export class HttpService {
constructor(private _http: Http){}
createPost(post: {title: string, body: string, userId: number}): Observable<any>{
const body = JSON.stringify(post);
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-urlencoded');
return this._http.post('http://localhost:8080/au', body, {
headers: headers
}).map(res => res.json());
}
}
然后我在 app.component.ts 中添加了一个按钮的简单输入:
import {Component} from 'angular2/core';
import {HttpService} from './http.service';
@Component({
selector: 'my-app',
template: `
<div>
<div class="input">
<label for="title">Title</label>
<input type="text" id="title" #title>
</div>
<div class="input">
<label for="body">Body</label>
<input type="text" id="body" #body>
</div>
<div class="input">
<label for="user-id">User ID</label>
<input type="text" id="user-id" #userId>
</div>
<button (click)="onPost(title.value, body.value, userId.value)">Post Data</button>
</div>
`,
providers: [HttpService]
})
export class AppComponent {
response: string;
constructor(private _httpService: HttpService){}
onPost(title: string, body: string, userId: string){
this._httpService.createPost({title: title, body: body, userId: +userId})
.subscribe(
response => this.response = response,
error => console.log(error)
)
}
}
然后在 Java 应用程序中使用 @CrossOrigin 注释在我的 UserController 中创建一个简单的方法并创建内部类 Post。
@CrossOrigin(origins = "http://localhost:3000")
@RequestMapping(value = "/au", method = RequestMethod.POST)
public ResponseEntity<Void> au(@RequestBody Post post){
System.out.println(post.getBody() + " " + post.getTitle() + " " + post.getUserId());
return new ResponseEntity<Void>(HttpStatus.OK);
}
public class Post {
private String title, body;
private int userId;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
}
但是当我启动这两个应用程序并单击发布按钮时 - 我有 XMLHttpRequest cannot load 和 HTTP status code 403。我还需要做什么才能发送 POST?
【问题讨论】:
-
“连接”是什么意思?有什么问题?您收到
Access-Control-Allow-...错误吗? -
我的意思是,我有一个带有 DB 的 Java 应用程序。如何在 Angular 的 2 主页(index.html)中从 DB 中写入登录名和密码并登录?
-
已编辑。我认为“注入”是正确的,而不是“连接”
-
我想说这个问题太宽泛了。
-
也许你有一个简单的例子或类似的东西?我的意思是,如何将 Angular 2 与 Java 一起使用?
标签: java http angular spring-boot