#CORS POST ERROR / Localhost

2 messages · Page 1 of 1 (latest)

lofty bloom
#

Hello!

I'm creating a just a simple CRUD Angular & Codeigniter for the Backend,

Everything is working with my API ( Tried with Postman )

But when i want to post my request, i have a CORS ERROR

Access to XMLHttpRequest at 'http://localhost:8081/api/task' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

I had the same before, when i was getting the DATA,
so i did a proxy conf

{
  "/api/**": {
    "target": "http://localhost:8081",
    "secure": false,
    "logLevel": "debug",
    "changeOrigin": true
  }
}

angular.json

"serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "configurations": {
            "production": {
              "browserTarget": "X:build:production",
              "proxyConfig": "src/proxy.conf.json"
            },
            "development": {
              "browserTarget": "X:build:development",
              "proxyConfig": "src/proxy.conf.json"
            }
          },
          "defaultConfiguration": "development"
        },

service

addTask(task: Task) {
    return this.http.post<Task>('http://localhost:8081/api/task', task);
  }

component

onAddTask(form: NgForm) {
    const value = form.value;
    const newTask = new Task(value.name, value.description);
    this.taskService.addTask(newTask).subscribe((task: Task) => {
      console.log(task);
    });

    form.reset();
  }
spark bison
#

If you send a request to http://localhost:8081/api/task, then you're sending the request directly to your API server, without going through the proxy, which runs on port 4200, and then "transfers" all the requests starting with /api/ to the API server (and transfers the responses from the server back to the browser).
So, send the requests to /api/task, not to http://localhost:8081/api/task.
But that will solve your issue during development. Where and how do you plan to deploy this application in production? Depending on what you want, you could have to configure the API to accept CORS requests anyway.