How can i connect frontend with backend and post objects from frontend to backend

huangapple go评论80阅读模式
英文:

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 端点上,我得到的是:

How can i connect frontend with backend and post objects from frontend to backend

同时在 Spring 中也出现了这个错误:

已解决 [org.springframework.web.HttpRequestMethodNotSupportedException: 请求方法 'GET' 不受支持],但我没有使用 "GET",不知道为什么。

很遗憾,我真的不明白为什么会有 "GET" 方法,以及为什么我的 POST 请求不起作用。也许有人可以帮助我。谢谢。

英文:

So i have the following ngOnInit() for test:

ngOnInit(): void {
    this.http.post&lt;any&gt;(&#39;http://localhost:8080/api/answers&#39;, { title: &#39;Angular POST Request Example&#39; });
  }

And the following RestController:

@RestController
@RequestMapping(&quot;/api&quot;)
public class ControllerPosting{


    @PostMapping(path=&quot;/answers&quot;, produces = MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody String handlePostRequest(@RequestBody String title){
        //System.out.println(s);
        return &quot;ok&quot;;
    }
}

What i get on the /api/answers side is:
How can i connect frontend with backend and post objects from frontend to backend

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

huangapple
  • 本文由 发表于 2023年4月17日 20:19:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76035100.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定