The CORS policy has blocked access to 'http://localhost:8080/BeginSignup' from 'http://localhost:4200'

I'm having trouble with a CORS policy error when sending a fetch POST request to my Golang AppEngine API. Although I don't understand why this error is occurring. Below is the code I'm using:

Below is the Angular code calling the API:

private async sendHTTPPut(data: UserInfo, func: string) {
    let requestHeaders = { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' } as HeadersInit;

    console.log(requestHeaders)

    return await fetch(
        this.endpoint + func,
        {
          method: 'POST',
          headers: requestHeaders,
          body: JSON.stringify(data),
          mode: "cors"
        }
    )
  }

Here is the server code handling CORS:

func StartApp() {
    router = mux.NewRouter()

    router.HandleFunc("/", hello)
    router.HandleFunc("/hello", hello)
    router.HandleFunc("/AcceptMember", AcceptMember)
    router.HandleFunc("/CreateTeam", CreateTeam)
    router.HandleFunc("/Leave", Leave)
    router.HandleFunc("/InviteMember", InviteMember)
    router.HandleFunc("/BeginSignup", BeginSignup)
    router.HandleFunc("/ProcessSignup", ProcessSignup)
    router.HandleFunc("/CompleteSignup", CompleteSignup)
    // Scoring
    router.HandleFunc("/GetLocalScore", GetLocalScore)

    allowedOrigins := handlers.AllowedOrigins([]string { "* always" })
    allowedHeaders := handlers.AllowedHeaders([]string { "Content-Type" })

    if err := http.ListenAndServe(":8080", handlers.CORS(allowedOrigins, allowedHeaders)(router)); err != nil {
        log.Fatal(err)
    }
}

Shown below is the request sent to the server:

Request URL: http://localhost:8080/BeginSignup
Referrer Policy: no-referrer-when-downgrade

Provisional headers are shown
Access-Control-Allow-Origin: *
Content-Type: application/json
Referer: http://localhost:4200/
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36 Edg/85.0.564.68

PAYLOAD
{member: {phoneNum: "0648503047"},…}
member: {phoneNum: "0648503047"}
score: null
team: {teamName: ".None", teamMembers: ["0648503047"], teamLeader: "0648503047"}

Here is the response received from the server:

Request URL: http://localhost:8080/BeginSignup
Request Method: OPTIONS
Status Code: 200 OK
Remote Address: [::1]:8080
Referrer Policy: no-referrer-when-downgrade
Content-Length: 0
Date: Mon, 05 Oct 2020 20:34:51 GMT
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Access-Control-Request-Headers: access-control-allow-origin,content-type
Access-Control-Request-Method: POST
Connection: keep-alive
Host: localhost:8080
Origin: http://localhost:4200
Referer: http://localhost:4200/
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36 Edg/85.0.564.68

Answer №1

When using angular in development mode with `ng serve`, the CORS error typically originates from angular itself.

To resolve this issue, you need to create a `proxy.conf.json` file with entries for your various endpoints within the `src` directory:

{
    "/api/*": {
        "target": "http://localhost:<your-port>",
        "secure": false,
        "logLevel": "debug"
    }
}

Additionally, make sure to reference this file in your `angular.json` configuration:

"serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "<your-app>:build",
            "proxyConfig": "src/proxy.conf.json"
          },
          ...
        },

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a Node.js asynchronous setup function

I'm in the process of transitioning from Nodejs v12 to v14 and I've noticed that v14 no longer waits for the setup function to resolve. My setup involves Nodejs combined with Express. Here's a simplified version of my code: setup().then(cont ...

Verifying currency in mat-input field

I need help implementing validation for inputting prices on a form. For example, if a user types in $20.0000, I want a validation message to appear marking the input as invalid. Would this type of validation require regex, and if so, how would I go about ...

Creating a .d.ts file for a JavaScript file that exports a plain object - tips and best practices

I am attempting to include a .d.ts file for an existing js file. The type.js file looks like this: // type.js export default { NORMAL: '001', CHECK: '002', }; Now, I have added a type.d.ts file as follows: // type.d.ts decla ...

In React Typescript, there is an issue with react-router v4 where the Route component does not pass its props to the specified component

Struggling with React Router v4 and history usage in Browserrouter. Whenever attempting to access this.props.history.push("/"), the error pops up: TS2339: Property 'history' does not exist on type 'Readonly<{ children?: ReactNode; }> ...

How do I assign a default value to an optional parameter in a derived class in Typescript?

One of my classes is called ClientBase: export class ClientBase { constructor(private uri: string, private httpClient: HttpClient) { } // Contains Various Methods } I have multiple subclasses that are derived from the ClientBase For instance: @I ...

Encountering an error with RouterLink: 'frequency' property is undefined

In my Angular 4 project, I am encountering an issue with the following HTML code in my view: <p> You are on dashboard (first level); <a [routerLink]="['/second-dashboard', {frequency: frequency, datefrom: datefromparam, dateto: ...

Angular facing issue with loading data and not displaying on time

In my project, I am facing difficulty in displaying the users' data on the user interface (UI). Despite trying to display the data, I am encountering issues. Here is the data from my users.json file: { "success": true, "summary": { "total_reg ...

Changing the background color of .pane and .view elements in an Ionic web application using JavaScript

Looking to modify the background-color of two css selectors, .pane and .view, that are located within the ionic.css file. Despite multiple attempts to do so using JavaScript directly in the index.html file, the changes are not reflected. The code snippet ...

Is it possible to utilize a const as both an object and a type within TypeScript?

In our code, we encountered a scenario where we had a class that needed to serve as both an object and an interface. The class had a cumbersome long name, so we decided to assign it to a constant. However, when we attempted to use this constant, we faced s ...

Using the as operator in TypeScript for type casting a string

function doSomething(a : any) { let b = (a as Array<any>) alert(typeof b) // displays "string" } doSomething("Hello") The alert is showing "string" instead of what I anticipated, which was something along the lines of a null value. The docu ...

What method can be used to inherit the variable type of a class through its constructor

Currently, I am in the process of creating a validator class. Here's what it looks like: class Validator { private path: string; private data: unknown; constructor(path: string, data: string) { this.data = data; this.path = path; } ...

Limiting Access for Clients in Node.js/Express Application

Recently, I developed a innovative Node.js application which is responsible for editing a MongoDB database upon receiving an HTTP request from an iOS app. The iOS app communicates with the server through specific routes determined by Express to specify t ...

The JavaScript file fails to load when accessing port 8080

As I embark on my journey into backend development, please bear with me. Currently, I am working on a JavaScript program that retrieves text data from my localhost. I have set up an HTTP server using Node.js which serves as a regular HTTP server. The serve ...

Issue: Failed to Render: Error encountered during parsing of template: Element 'mat-checkbox' is not recognized as a valid element

For the purpose of testing my component, I wrote the following code snippet: describe('Component: TestComponent', () => { let component: TestComponent; let fixture: ComponentFixture<TestComponent>; beforeEac ...

Issue with Angular 9 application: Unable to properly render form fields within a Material Design Dialog

I'm currently developing a "Tasks" application using Angular 9 and PHP. I've encountered an error that says Cannot find control with name: <control name> when attempting to pre-fill the update form with data. Here is the form template: &l ...

Is subtyping causing issues in TypeScript's inheritance model?

I am currently utilizing TypeScript for my coding projects, and I have observed that it can allow the production of non-type-safe code. Despite implementing all the "strict" options available to me, the behavior I am experiencing goes against the principle ...

Differences in file sizes in Angular-CLI builds

After building my Angular app, I noticed the following output: https://i.sstatic.net/ZRtxU.png Upon closer inspection, it is evident that 0.7f787ebcd865a23bb4ea.chunk.js and vendor.fbdfd024192bddab02d3.bundle.js are quite large. To confirm their sizes, ...

Issue encountered while attempting to start a project using Ionic

After cloning a repository using the git clone command and running npm install, I encountered a message with warnings about vulnerabilities: npm WARN deprecated" and at the end it says "55 vulnerabilities (3 low, 12 moderate, 36 high, 4 critical) To addres ...

Ways to improve page loading speed in Angular 4

Completed a project using Angular 4 with a .Net web API backend. Encountering slow loading times of 1 to 2 minutes consistently when trying to access my website. While familiar with lazy loading and module division concepts, unable to implement them curr ...

Managing JSON object with irregular data in Angular 7: Best Practices

When the service returns data in a specific format, I am able to view the data in the developer tools. {"results":{"BindGridDatatable":[{"ID":"0005","Name":"Rohit"}, {"ID":"0006","Name":"Rahul"}], "Totalvalue":119}} ...