-2

I have a problem with this CURL request. It works fine if I send it over terminal but when I convert it to Angular HTTP Client call it doesn't work.

Curl:

curl --location --request PUT '<some_url>' \
--header 'Accept: application/json' \
--header 'Content-Type: application/json' \
--data-raw '{
    "status": "CONFIRMED"
}'

Angular:

const headers = new HttpHeaders()
  .set('Content-Type', 'application/json')
  .set('Accept', 'application/json; charset=UTF-8');

const b = {
  status: 'CONFIRMED'
};

return this.http.put(some_url, b, { headers });

Error: Access to <some_url> from origin 'http://localhost:4200' has been blocked by CORS policy: Method PUT is not allowed by Access-Control-Allow-Methods in preflight response.

Gregor A
  • 217
  • 5
  • 16

3 Answers3

1

Try this code :

const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
        'Accept', 'application/json; charset=UTF-8'
      }),
    };
const b = {
  status: 'CONFIRMED'
};
return this.http<any>(some_url, b,httpOptions)
      .pipe(catchError(this.errorHandler));

use a proxy.config.json file

 {
      "/api/*": {
        "target": "http://backendurl",
        "secure": false,
        "changeOrigin": true
      }
    }

add the proxy configuration the angular.json under the serve->options :

  "serve": {
    "builder": "@angular-devkit/build-angular:dev-server",
    "options": {
      "browserTarget": "your-application-name:build",
      "proxyConfig": "src/proxy.conf.json" // add this ligne
    },
  • ` const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Accept', 'application/json; charset=UTF-8' }), }; ` Aren't necessary, except from this, everything will work fine but. – StPaulis Oct 23 '20 at 12:28
0
return this.http.put(some_url, body);

Should work.

StPaulis
  • 2,844
  • 1
  • 14
  • 24
  • It doesn't: has been blocked by CORS policy: Method PUT is not allowed by Access-Control-Allow-Methods in preflight response. – Gregor A Oct 23 '20 at 11:30
  • OK, that's another problem. See here: https://stackoverflow.com/questions/50237881/angular-cors-request-blocked/50242631 – StPaulis Oct 23 '20 at 11:35
0

Make sure to call subscribe() after the put(), otherwise the request won't be executed at all.

SurfMan
  • 1,685
  • 12
  • 19