CORS: Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true

后端 未结 9 2504
借酒劲吻你
借酒劲吻你 2020-11-22 01:54

I have a setup involving

Frontend server (Node.js, domain: localhost:3000) <---> Backend (Django, Ajax, domain: localhost:8000)

Browser <-- webapp <

相关标签:
9条回答
  • 2020-11-22 02:34

    If you are using CORS middleware and you want to send withCredential boolean true, you can configure CORS like this:

    var cors = require('cors');    
    app.use(cors({credentials: true, origin: 'http://localhost:3000'}));
    
    0 讨论(0)
  • 2020-11-22 02:37

    (Edit) The previously recomended add-on is not available any longer, you may try this other one


    For development purposes in Chrome, installing this add on will get rid of that specific error:

    Access to XMLHttpRequest at 'http://192.168.1.42:8080/sockjs-node/info?t=1546163388687' 
    from origin 'http://localhost:8080' has been blocked by CORS policy: The value of the 
    'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' 
    when the request's credentials mode is 'include'. The credentials mode of requests 
    initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
    

    After installing, make sure you add your url pattern to the Intercepted URLs by clicking on the AddOn's (CORS, green or red) icon and filling the appropriate textbox. An example URL pattern to add here that will work with http://localhost:8080 would be: *://*

    0 讨论(0)
  • 2020-11-22 02:39

    try it:

    const cors = require('cors')
    
    const corsOptions = {
        origin: 'http://localhost:4200',
        credentials: true,
    
    }
    app.use(cors(corsOptions));
    
    0 讨论(0)
  • 2020-11-22 02:42

    This is a part of security, you cannot do that. If you want to allow credentials then your Access-Control-Allow-Origin must not use *. You will have to specify the exact protocol + domain + port. For reference see these questions :

    1. Access-Control-Allow-Origin wildcard subdomains, ports and protocols
    2. Cross Origin Resource Sharing with Credentials

    Besides * is too permissive and would defeat use of credentials. So set http://localhost:3000 or http://localhost:8000 as the allow origin header.

    0 讨论(0)
  • 2020-11-22 02:44

    If you are using express you can use the cors package to allow CORS like so instead of writing your middleware;

    var express = require('express')
    , cors = require('cors')
    , app = express();
    
    app.use(cors());
    
    app.get(function(req,res){ 
      res.send('hello');
    });
    
    0 讨论(0)
  • 2020-11-22 02:51

    If you want to allow all origins and keep credentials true, this worked for me:

    app.use(cors({
      origin: function(origin, callback){
        return callback(null, true);
      },
      optionsSuccessStatus: 200,
      credentials: true
    }));
    
    0 讨论(0)
提交回复
热议问题