How can I resolve Angular CORS Policy errors when trying to post data to an API?

Discussão em 'Angular' iniciado por Abdulrashid Sani Imam, Dezembro 28, 2024.

  1. I am trying to post a form data to an API from an angular application running on localhost, and my code is as follows:

    submitdata(){
    this.http.post(this.url, this.fg.value, {observe: 'body'} ).subscribe((response: any)=>{
    console.log(response.body)
    })
    }


    but every time I send the data to the API which is also running on my local computer, the browser gives me the following errors:


    Access to XMLHttpRequest at 'localhost:5000/home' from origin 'http://localhost:4200' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: chrome, chrome-extension, chrome-untrusted, data, http, https, isolated-app.
    ​

    On the API endpoint I installed cors to an express node.js server and set the origin to http://localhost:4200 but still the errors persist.

    I tried different CORS policy configurationn in the express server and even allowed all origins to connect to the API but to no avail, like this:

    app.use(cors({
    origin: "http://localhost:4200"

    }))


    when it didn't work I tried setting the response header with Access-Control-Allow-Origin to true but that too didn't solve the problem.

    and finally I got frustrated and I shutdown the server and to see what the error will be and that's when I found out that the request is not even reaching the server and Angular keeps telling me the request is blocked by CORS policy.

    I am feeling like the problem is from angular httpClient I use to make the request to the API, but in any case what am I missing please?

    Continue reading...

Compartilhe esta Página