Angular 2 http post params and body

前端 未结 5 2034
暖寄归人
暖寄归人 2021-02-02 16:32

I\'m trying to do an api call from my angular app. What I want to do is send a post request to the api with a command param. I have done a lot of server side testing as well as

相关标签:
5条回答
  • 2021-02-02 16:37

    Let said our backend looks like this:

    public async Task<IActionResult> Post([FromBody] IList<UserRol> roles, string notes) {
    }
    
    

    We have a HttpService like this:

        post<T>(url: string, body: any, headers?: HttpHeaders, params?: HttpParams): Observable<T> {
            return this.http.post<T>(url, body, { headers: headers, params});
        }
    

    Following is how we can pass the body and the notes as parameter: // how to call it

    const headers: HttpHeaders = new HttpHeaders({
        'Authorization': `Bearer XXXXXXXXXXXXXXXXXXXXXXXXXXX`
    });
    
    const bodyData = this.getBodyData(); // get whatever we want to send as body
    
    let params: HttpParams = new HttpParams();
    params = params.set('notes', 'Some notes to send');
    
    this.httpService.post<any>(url, bodyData, headers, params);
    
    

    It worked for me (using angular 7^), I hope is useful for somebody.

    0 讨论(0)
  • 2021-02-02 16:40

    The 2nd parameter of http.post is the body of the message, ie the payload and not the url search parameters. Pass data in that parameter.

    From the documentation

    post(url: string, body: any, options?: RequestOptionsArgs) : Observable<Response>

    public post(cmd: string, data: object): Observable<any> {
    
        const params = new URLSearchParams();
        params.set('cmd', cmd);
    
        const options = new RequestOptions({
          headers: this.getAuthorizedHeaders(),
          responseType: ResponseContentType.Json,
          params: params,
          withCredentials: false
        });
    
        console.log('Options: ' + JSON.stringify(options));
    
        return this.http.post(this.BASE_URL, data, options)
          .map(this.handleData)
          .catch(this.handleError);
      }
    

    Edit

    You should also check out the 1st parameter (BASE_URL). It must contain the complete url (minus query string) that you want to reach. I mention in due to the name you gave it and I can only guess what the value currently is (maybe just the domain?).

    Also there is no need to call JSON.stringify on the data/payload that is sent in the http body.

    If you still can't reach your end point look in the browser's network activity in the development console to see what is being sent. You can then further determine if the correct end point is being called wit the correct header and body. If it appears that is correct then use POSTMAN or Fiddler or something similar to see if you can hit your endpoint that way (outside of Angular).

    0 讨论(0)
  • 2021-02-02 16:51

    Seems like you use Angular 4.3 version, I also faced with same problem. Use Angular 4.0.1 and post with code by @trichetricheand and it will work. I am also not sure how to solve it on Angular 4.3 :S

    0 讨论(0)
  • 2021-02-02 16:55

    And it works, thanks @trichetriche. The problem was in my RequestOptions, apparently, you can not pass params or body to the RequestOptions while using the post. Removing one of them gives me an error, removing both and it works. Still no final solution to my problem, but I now have something to work with. Final working code.

    public post(cmd: string, data: string): Observable<any> {
    
        const options = new RequestOptions({
          headers: this.getAuthorizedHeaders(),
          responseType: ResponseContentType.Json,
          withCredentials: false
        });
    
        console.log('Options: ' + JSON.stringify(options));
    
        return this.http.post(this.BASE_URL, JSON.stringify({
          cmd: cmd,
          data: data}), options)
          .map(this.handleData)
          .catch(this.handleError);
      }
    
    0 讨论(0)
  • 2021-02-02 17:00

    Yes the problem is here. It's related to your syntax.

    Try using this

    return this.http.post(this.BASE_URL, params, options)
      .map(data => this.handleData(data))
      .catch(this.handleError);
    

    instead of

    return this.http.post(this.BASE_URL, params, options)
      .map(this.handleData)
      .catch(this.handleError);
    

    Also, the second parameter is supposed to be the body, not the url params.

    0 讨论(0)
提交回复
热议问题