2

Hi I am working in c# azure function and java-script. I have web page running locally and hitting azure function also in locally. Below is my azure function and it runs in

negotiate: [POST] http://localhost:7071/api/negotiate

[FunctionName("negotiate")]
    public static async Task<SignalRConnectionInfo> Run(
        [HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequest req, IBinder binder,
        ILogger log)
    {
        log.LogInformation("C# HTTP trigger function processed a request.");
        var data = await Authenticated(req, log);
        var connectionInfo = binder.Bind<SignalRConnectionInfo>(new SignalRConnectionInfoAttribute { HubName = "MapUpload", UserId = data });
        return connectionInfo;
    }

Then in local.settings.json I have configured

 "Host": {
    "CORS": "*"
  }

Below is my java-script code.

 <script>
   const connection = new signalR.HubConnectionBuilder()
   .withUrl('http://localhost:7071/api/')
   .configureLogging(signalR.LogLevel.Information)
   .build();

   connection.on('MapUpload', productOrdered);
   connection.onclose(() => console.log('disconnected'));

   console.log('connecting...');
   connection.start()
   .then(() => data.ready = true)
   .catch(console.error);
</script>

When I run run my javascript application I get below error

Access to XMLHttpRequest at 'http://localhost:7071/api/negotiate' from origin 'http://localhost:3872' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: 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.

I have added "CORS": "*" but still gives me above error. So May I know Is there configurations I am missing in the above code. Can someone help em to understand this issue? Any help would be greatly appreciated. Thank you

Mr Perfect
  • 585
  • 8
  • 30

1 Answers1

7

As per fetch spec, To use credentials with cors mode, You need to set

  • Access-Control-Allow-Credentials to true and
  • Access-Control-Allow-Origin should NOT be set to *

Translating to local.settings.json,

 "Host": {
    "CORS": "http://localhost:3872",
    "CORSCredentials":true
  }
TheMaster
  • 45,448
  • 6
  • 62
  • 85
  • Just quick info In the above js codeI want to send jwt token. So how can i send? I tried something like this const options = { "Authorization":"MyToken"} then .withUrl('http://localhost:7071/api/', options) but token is not coming in azure function. Is that correct way I am sending? – Mr Perfect Aug 29 '20 at 07:44
  • 1
    @MrPerfect Kindly ask a new question. (That seems correct. You might wanna add "Bearer MyToken". Also documentation seems to suggest all localhost functions run anonymously. But am not a expert in azure, but cors) – TheMaster Aug 29 '20 at 07:50