Blocked by CORS policy error when calling to mongo/golang db with angular web app

ineedtoknow :

I'm making a web app with angular on the frontend, and golang and mongo on the backend for the database. I have the db up and running, and all route requests have been tested and are working on Postman. However, when I try to make DELETE request or PUT request on the service of the angular app, I get hit with the following error:

"Access to XMLHttpRequest at '-my api url-' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource."

I can make GET and POST requests, but not DELETE or PUT.

How do I get around this? Is this a frontend issue, or backend? Any help will be appreciated. Thank you.

PS: I'm using mongoHandlers.

Here's my service on the front end:

deleteShow(showId: string) {
    let headers = new HttpHeaders();
    headers.append("Content-Type", "application/json");
    return this.http
      .delete<Show>(`${environment.apiBase}/shows/${showId}`, {
        headers
      })
      .pipe(catchError(this.handleError));
  }

Backend Code:

Route:

func RouteShows(r *mux.Router, shows handlers.ShowHandler) {

    sub := r.PathPrefix("/api/shows").Subrouter()

    sub.HandleFunc("", getShows(shows)).Methods(http.MethodGet)
    sub.HandleFunc("/{id}", getShowById(shows)).Methods(http.MethodGet)
    sub.HandleFunc("/{id}", updateShow(shows)).Methods(http.MethodPut)
    sub.HandleFunc("", createShow(shows)).Methods(http.MethodPost)
    sub.HandleFunc("/{id}", deleteShow(shows)).Methods(http.MethodDelete)
    sub.HandleFunc("/status/{status}", getShowsByStatus(shows)).Methods(http.MethodGet)
}

API func:

func deleteShow(s handlers.ShowHandler) http.HandlerFunc {

    return func(w http.ResponseWriter, r *http.Request) {

        params := mux.Vars(r)
        var show models.Show

        if _, ok := params["id"]; !ok {
            responses.BadRequestWrapped(w, errors.New("param not found: id"))
            return
        }

        err := s.DeleteShow(params["id"])
        if err != nil {
            responses.InternalServerErrorWrapped(w, errors.FromError(err)) //TODO
            return
        }

        responses.OK(w, show)
    }

}

MongoHandler interface:

//ShowHandler handles the interface of mongo func
type ShowHandler interface {
    SearchShows(values map[string][]string, pagination *models.Pagination) ([]*models.Show, error)
    GetShows() ([]*models.Show, error)
    GetShowById(id string) (*models.Show, error)
    //GetAppointmentsCreatedByUser(username string) ([]*models.Appointment, error)
    GetShowsByStatus(status string) ([]*models.Show, error)

    CreateShow(show *models.Show) error
    UpdateShow(show *models.Show) error
    DeleteShow(id string) error
}

Mongo Handler:

//deleteShow removes a show based on Show ID from DB
func (s *shows) DeleteShow(id string) error {

    if _, err := s.mongo.DeleteOne(db_qcq, collection_shows, ValueEquals("_id", id)); err != nil {
        return err
    }

    return nil
}

Hope this is enough to give perspective.

Bhagvat Lande :

I think the issue is not on the angular side, It looks NodeJs server is blocking DELETE request. You need to allow this request types on a node server.

Note - CORS: Cross-Origin Resource Sharing, that means you need to tell server from which are the valid source, and which are the valid Http method types are allowed on request. (I have added * that means all source allowed)

You can use below code (if using express)

// Initialize express middleware 
const express = require('express');
const app = express();

// Enable CORS
app.use(function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT,DELETE");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
    next();
});

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Getting an error "blocked by CORS policy" only for "https://localhost:44361/connect/token" in Angular 7 web app

From Dev

XMLHttpRequest blocked by CORS policy when posting data to a Web App

From Java

Requests from angular app blocked by CORS policy in spring app

From Dev

Getting Around "blocked by CORS policy" Error in Angular App Running Local Instance of API

From Dev

Blocked By CORS Policy Angular and Slim

From Dev

CORS policy blocked on Angular / NGINX

From Dev

Access to XMLHttpRequest from origin has been blocked by CORS policy ( Vue.JS app calling Lumen App )

From Dev

Access to web manifest blocked by CORS policy

From Dev

blocked by CORS policy in ionic-5 angular

From Dev

Google App Script Web App GET and POST request blocked by CORS policy

From Dev

CORS policy error while calling remote URL in Angular

From Android

Google Play Store Fails to upload app icon with "blocked by CORS policy" error

From Java

Angular 6 + Spring Boot: Error: "from origin 'http://localhost:4200' has been blocked by CORS policy"

From Dev

Getting error has been blocked by CORS policy when making api call

From Dev

Request is blocked by CORS policy

From Dev

Error: Access to XMLHttpRequest at https://storage.googleapis.com/url from origin has been blocked by CORS policy. In angular when using gcp SignedURl

From Java

browser says " request has been blocked by CORS policy" when calling to a spring boot get method from react js using axios

From Dev

ionic app blocked by CORS policy, jsonp not working neither

From Dev

blocked by CORS policy: react js app issue. Axios

From Dev

Angular requests blocked by CORS policy only under certain conditions

From Dev

still get error on has been blocked by CORS policy

From Dev

Getting blocked by CORS policy error despite adding appropriate headers

From Dev

Google sheets web app blocked by CORS when trying to send a get request on the front-end

From Dev

Ajax POST blocked by CORS Policy

From Dev

Blazor Request blocked by CORS policy

From Java

Axios Request: Blocked by CORS Policy

From

'Blocked by CORS policy', but Header is present

From Dev

Fonts files blocked by CORS policy

From Dev

request blocked by cors policy on heroku

Related Related

  1. 1

    Getting an error "blocked by CORS policy" only for "https://localhost:44361/connect/token" in Angular 7 web app

  2. 2

    XMLHttpRequest blocked by CORS policy when posting data to a Web App

  3. 3

    Requests from angular app blocked by CORS policy in spring app

  4. 4

    Getting Around "blocked by CORS policy" Error in Angular App Running Local Instance of API

  5. 5

    Blocked By CORS Policy Angular and Slim

  6. 6

    CORS policy blocked on Angular / NGINX

  7. 7

    Access to XMLHttpRequest from origin has been blocked by CORS policy ( Vue.JS app calling Lumen App )

  8. 8

    Access to web manifest blocked by CORS policy

  9. 9

    blocked by CORS policy in ionic-5 angular

  10. 10

    Google App Script Web App GET and POST request blocked by CORS policy

  11. 11

    CORS policy error while calling remote URL in Angular

  12. 12

    Google Play Store Fails to upload app icon with "blocked by CORS policy" error

  13. 13

    Angular 6 + Spring Boot: Error: "from origin 'http://localhost:4200' has been blocked by CORS policy"

  14. 14

    Getting error has been blocked by CORS policy when making api call

  15. 15

    Request is blocked by CORS policy

  16. 16

    Error: Access to XMLHttpRequest at https://storage.googleapis.com/url from origin has been blocked by CORS policy. In angular when using gcp SignedURl

  17. 17

    browser says " request has been blocked by CORS policy" when calling to a spring boot get method from react js using axios

  18. 18

    ionic app blocked by CORS policy, jsonp not working neither

  19. 19

    blocked by CORS policy: react js app issue. Axios

  20. 20

    Angular requests blocked by CORS policy only under certain conditions

  21. 21

    still get error on has been blocked by CORS policy

  22. 22

    Getting blocked by CORS policy error despite adding appropriate headers

  23. 23

    Google sheets web app blocked by CORS when trying to send a get request on the front-end

  24. 24

    Ajax POST blocked by CORS Policy

  25. 25

    Blazor Request blocked by CORS policy

  26. 26

    Axios Request: Blocked by CORS Policy

  27. 27

    'Blocked by CORS policy', but Header is present

  28. 28

    Fonts files blocked by CORS policy

  29. 29

    request blocked by cors policy on heroku

HotTag

Archive