简体   繁体   中英

Unable to send POST request via HTTP in Angular 4

I am building a small Angular frontend support by a REST api in the backend, but I have ran into a very strange problem: doing http.post(url, data, params) results in nothing happening (there's no sign the request ever hits the webserver, in Chrome Developer tools there's absolutely no request logged as opposed to this.http.get() requests, which work fine for URLs on the same server).

export class RestComponent {

    constructor ( private http: Http ) {}
    sendStuff() {
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });

        this.http.post('http://localhost:3021/api/data', {'data': 3}, options)
            .catch(this.handleError);
    }
}
  • CORS is enabled on the server
  • this.http.get on the URL works as expected
  • there's no evidence in the server logs that the request was ever sent
  • there's no evidence in Chrome developer tools that the request was sent (no such post request)
  • logging stuff in the method just before the .post() call shows that everything is as expected (headers, data, etc)
  • replicating the request in Postman works (identical headers and data)
  • tried stringyfying the data as well
  • the error handler does some simple logging, but it's not triggered

I feel quite dumb as it must be something that's fairly obvious yet it escapes me. I've created a simple component which just two methods, one that sends hardcoded data via post and the other that fetches a hardcoded json via get, the second works but the first doesn't.

Would appreciate any pointers.

Thanks!

Essentially you had created just an observable and Observable are lazy in nature. They will get call/emit only when someone has subscribe to them. Hence you have to call subscribe to Observable returned from it to make your code working. Apart from this Everything seems to be perfect.

sendStuff() {
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });

    return this.http.post('http://localhost:3021/api/data', {'data': 3}, options)
      .catch(this.handleError)
      .subscribe(
       (data) => console.log(data)
    );
}

There's no server code for us to see but make sure that the route is setup to expect content-type application/json because by default a post route will expect post data, depending on what technology you are using for your server.

Also try just doing a relative path maybe: .post('/api/data')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM