Having trouble establishing a connection with SignalR on my backend, it just doesn't seem to work properly

I am currently working on a project where I am using Vue with TypeScript and @microsoft/signalr. My goal is to create a chat feature using SignalR, and on the backend, I am utilizing C# with ASP.NET Core and docker.

Here is the code snippet I have implemented on the backend:

 // Backend code snippet goes here

ChatHub class:

 // ChatHub class code snippet goes here

Now, moving on to the frontend:

 // Frontend code snippet goes here

In my ChatView.vue file, I am using the ChatService:

//...
 export default defineComponent({
        components: { Header},
        data() {
            return {
                store: store,
                chatService: {} as ChatService, 
                //...
            };
        },
        computed: {
        },
        mounted() {
        //...
            this.load_data();
        },
        methods: {
            load_data(){
                let chatService = container.resolve(ChatService);
                this.chatService = chatService;
                chatService.start(this.user.id, this.store.state.user!);
                this.messages = this.chatService.messages;
            },
        //...
        },
    })
    </script>

However, after calling load_data() and connection.start(), I encounter the following error message:

Access to fetch at 'http://localhost:8181/chat/negotiate?negotiateVersion=1' from origin 'http://localhost:5173' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.

@microsoft_signalr.js?v=12bba02c:2110 Uncaught (in promise) Error: Failed to complete negotiation with the server: TypeError: Failed to fetch at HttpConnection._getNegotiationResponse (@microsoft_signalr.js?v=12bba02c:2110:29)

ChatService.ts:35 [2024-06-03T18:17:15.726Z] Error: Failed to start the connection: Error: Failed to complete negotiation with the server: TypeError: Failed to fetch

ChatService.ts:35 [2024-06-03T18:17:15.725Z] Error: Failed

to complete negotiation with the server: TypeError: Failed to fetch

I have tried various CORS policy settings on the backend and different headers in connectionBuilder.WithUrl(...), but I am still facing this issue.

Answer №1

When using both SetIsOriginAllowed and WithOrigins together, you may encounter CORS issues. For more information, refer to this thread.

To resolve this, modify your CORS settings as shown below.

app.UseCors(policyBuilder =>
{
    policyBuilder.WithOrigins("http://localhost:5173")
        .AllowAnyHeader()
        .AllowAnyMethod()
        .AllowCredentials();
        //.SetIsOriginAllowedToAllowWildcardSubdomains()
        //.SetIsOriginAllowed((host) => true);
});

Additionally, it seems there are some middleware order issues in your code.

var app = builder.Build();
    
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

//app.UseAuthentication();
//app.UseAuthorization();
//app.UseSession();

app.UseCors(policyBuilder =>
{
    policyBuilder.WithOrigins("http://localhost:5173")
        .AllowAnyHeader()
        .AllowAnyMethod()
        .AllowCredentials();
        //.SetIsOriginAllowedToAllowWildcardSubdomains()
        //.SetIsOriginAllowed((host) => true);
});

app.UseAuthentication();
app.UseAuthorization();
// move it to here
app.UseSession();

app.MapControllers();

app.MapHub<ChatHub>("/chat");

app.Run();

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

"Vue is failing to actively update an input that relies on changes from another

I am working on a project where the selected country automatically determines the phone country code. I have set it up so that when I change the country, the corresponding country code should update as well. https://i.sstatic.net/861tq.png Within a custo ...

Exploring the process of extending Shoelace web components with Typescript using Lit

Once I extended the <sl-button> component in Lit, I realized that TypeScript was not catching errors for incorrect attributes being passed. For instance, in the code snippet provided below, when I use <sl-button> with an incorrect attribute, ...

TypeScript Firestore Reducer: A more efficient way to

I've been working on my reducers and have come across this piece of code: import { Reducer, combineReducers } from 'redux'; import { routerReducer } from 'react-router-redux'; import { firebaseReducer } from 'react-redux-fire ...

Using TypeScript in conjunction with Node.js

I'm currently trying to use typescript with nodejs, but I keep encountering errors. Can anyone help me troubleshoot? Here is the code snippet (assuming all necessary modules are imported): import routes from "./routes/routes"; let app = express(); ap ...

Is there something I'm overlooking, or is this behavior unusual for an "if statement"?

I am facing an issue with returning a value from a function. It seems like a simple task - just looping through my HTMLElements and returning the one I need. This problem is new to me, and I have spent a considerable amount of time debugging the code and ...

What is the best way to trigger a code block once an observable in Angular has completed all of its tasks?

I have an observable made from an array of form controls in Angular. I am using dropdowns and inputs to calculate the sum of all currencies in relation to one currency, and it works. However, my issue is that when I want to update the field itself, the v ...

What is the process for configuring PhpStorm to sync with TypeScript tsconfig.json in .vue files?

Vue.js (webpack + vueify) with TypeScript is my current setup. The ts configuration appears to be functioning, but only in .ts files. For instance, in tsconfig.json: "compilerOptions": { "strictNullChecks": false, So strictNullChecks works as expect ...

Error: The use of await in RequestPromise is not valid

I encountered a TSLint error stating "Invalid 'await' of a non-Promise value." in the line of code below: const response: RequestResponse = <RequestResponse>await this.apiRequest(uri); Additional code context: private apiRequest: Request ...

TypeScript Library encounters issues when importing a specific data type

I recently integrated a library into my Next.js application to manage layouts using useState in react-grid-layout. To make this work with TypeScript, I had to install the necessary package shown below: npm install --save @types/react-grid-layout The code ...

What causes the discrepancy in values displayed by enums in TypeScript when assigned integers in reverse order?

Recently diving into the world of TypeScript, I've been experimenting with different types in this language. One interesting data type I played with is enums. Here's an example of code I used: enum colors {red=1,green=0,blue,white}; console.lo ...

Is there a way to refresh autocomplete/autofill after form submission with a custom JavaScript function?

I've developed a Vue application that includes a form. Once the user clicks on submit, an Ajax request is made using Axios through a JavaScript function. The data being sent is a custom JSON object that I have constructed by combining the information ...

Vue.js - encountering an issue with undefined response data

Greetings! I've encountered a script issue while trying to submit a form in VUE. The error message displayed in the developer panel states: "TypeError: error.response.data.errors is undefined". As a newcomer to Vue, I'm seeking some assistance as ...

Is there a way to showcase various category._id within a single page route using Vue.js?

When trying to display multiple categories under a route, clicking on the first category shows the products. However, when clicking on another category, the products do not show up unless I hard refresh the page, which then displays the list of products un ...

Mastering the usage of Higher Order Components (HOC) with both types of props is

I am facing a challenge in implementing HOCs for this specific scenario. I aim to enclose existing components since they share similar functionalities. Below is an abridged version of my current structure: function CreateComponentHere(props: BaseProps): J ...

The array is filled with values, however, there seems to be an issue preventing their access. What could possibly be causing this obstacle

After receiving two string values through a callback function, let's call them a and b, I attempt to store them in an array. However, when I check the array using console.log, it only displays the values if I expand the array by clicking on the arrow ...

Tips on mapping API response to the data attribute in Nuxt framework

I am currently in the process of modifying a section within a form. In this section, I will retrieve data using the content's id from an API. My goal is to map the returned data into an array in the data property so that it can be easily patched. Bel ...

Troubleshooting problem with v-for to display every Laravel error in a Vue component utilizing Axios

I'm attempting to display all Laravel errors using vue. I have successfully retrieved the output, but I am unsure how to format it properly. Vue Component data() { return { status: '', submitte ...

Incorporate Ng-Survey multiple times within one component

Incorporating the ng-surveys template into my Angular application via has been successful. However, I encountered an issue where when using the template selector *ngFor to display multiple surveys on the same page, the browser treats all the surveys as id ...

Accessing the state from a child functional component and then adding it to an array of objects in the parent component

I'm facing a challenge with a parent component that needs to manage the data of its child components stored in an array of objects. My goal is to add new child components and maintain their information within the parent's state as an array of obj ...

What is the best way to set up TypeScript interfaces using predefined string literals to limit the possible data types for shared attributes?

In this scenario, we have two interfaces named A and B with validation and variant properties. The goal is to create an Example object by using only the variant and validation values provided (since field is already defined). However, I encountered an erro ...