How to enable Access-Control-Allow-Origin for angular 5/nodejs?

前端 未结 4 490
名媛妹妹
名媛妹妹 2021-01-20 16:43

Read many ways for including of \'Access-Control-Allow-Origin\' and none worked for me.

I use @angular/common/http module and external url as data source. by the att

相关标签:
4条回答
  • 2021-01-20 17:11

    You mentioned webpack-dev-server, which of course can handle CORS since it's using express behind the scenes. In your webpack config

    devServer: {
      headers: {
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS",
        "Access-Control-Allow-Headers": "X-Requested-With, content-type, Authorization"
      }
    },
    
    0 讨论(0)
  • 2021-01-20 17:25

    **Set headers to allow CORS origin in Express **

    => Add code in the server.js file or mail file.

    app.use(function(req, res, next) {
       res.header("Access-Control-Allow-Origin", "*");
       res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
      next();
     });
    

    CORS (Cross-Origin Resource Sharing) is an HTML5 feature that allows one site to access another site’s resources despite being under different domain names.

    The W3C specification for CORS actually does a pretty good job of providing some simple examples of the response headers, such as the key header, Access-Control-Allow-Origin, and other headers that you must use to enable CORS on your web server.

    0 讨论(0)
  • 2021-01-20 17:31
    Access-Control-Allow-Origin
    

    Is response header not request header. You must add this header to your resfull (server)

    0 讨论(0)
  • 2021-01-20 17:36

    If you are using .NET Api then add this to your WebApiConfig.cs file

        public static void Register(HttpConfiguration config)
        {
            var enableCorsAttribute = new EnableCorsAttribute("*",
                                               "Origin, Content-Type, Accept",
                                               "GET, PUT, POST, DELETE, OPTIONS");
            config.EnableCors(enableCorsAttribute);
            // Web API configuration and services
            // Configure Web API to use only bearer token authentication.
            config.SuppressDefaultHostAuthentication();
            config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
    
            // Web API routes
            config.MapHttpAttributeRoutes();
    
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/v1/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
    
    0 讨论(0)
提交回复
热议问题