英文:
How can i connect frontend with backend and post objects from frontend to backend
问题
I can help you with the translation. Here's the translated content:
所以我有以下的 ngOnInit()
用于测试:
ngOnInit(): void {
this.http.post<any>('http://localhost:8080/api/answers', { title: 'Angular POST Request Example' });
}
还有以下的 RestController:
@RestController
@RequestMapping("/api")
public class ControllerPosting{
@PostMapping(path="/answers", produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody String handlePostRequest(@RequestBody String title){
//System.out.println(s);
return "ok";
}
}
在 /api/answers
端点上,我得到的是:
同时在 Spring 中也出现了这个错误:
已解决 [org.springframework.web.HttpRequestMethodNotSupportedException: 请求方法 'GET' 不受支持],但我没有使用 "GET",不知道为什么。
很遗憾,我真的不明白为什么会有 "GET" 方法,以及为什么我的 POST 请求不起作用。也许有人可以帮助我。谢谢。
英文:
So i have the following ngOnInit() for test:
ngOnInit(): void {
this.http.post<any>('http://localhost:8080/api/answers', { title: 'Angular POST Request Example' });
}
And the following RestController:
@RestController
@RequestMapping("/api")
public class ControllerPosting{
@PostMapping(path="/answers", produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody String handlePostRequest(@RequestBody String title){
//System.out.println(s);
return "ok";
}
}
What i get on the /api/answers side is:
Also getting this error in spring:
Resolved [org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' is not supported] but im not using "GET" dont know..
Sadly, i realy don't understand why there is method "GET" and why my post isn't there. Perheps someone can help me. Thank you.
答案1
得分: 1
通过在浏览器中输入 localhost:8080/api/request
,您正在发送 GET 请求到 http://localhost:8080/api/request
,而且这是后端而不是前端。您没有在后端处理 GET 请求 - 这就是为什么您会收到状态码 405 (方法不允许)。
我猜您想要进入前端。Angular 应用程序的默认端口是 4200,所以您应该尝试在浏览器中输入 localhost:4200
。
英文:
By entering localhost:8080/api/request
in your browser you are sending GET request to http://localhost:8080/api/request
and this is your backend not fronted. You are not handling GET request on the backend - that is why you are getting status 405 (method not allowed).
I bet what you wanted was to enter the fronted. The default port for the angular app is 4200 so you should try to enter into the browser localhost:4200
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论