Unable to access due to CORS restriction on Express server

Whenever I attempt to send a POST api request to my express server, I encounter the following error message.

Access to XMLHttpRequest at 'localhost:8081/application' from origin 'localhost:8083' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

The express server utilizes the npm cors package and passport jwt authentication strategy.

privateServer.use(cors());
registerJWTAuthentication();
  privateServer.all('*', authenticate('jwt', {
    session: false,
  }));
privateServer.addRouter('/application', privateApplicationRouter);

I am using axios to send this request from a nuxtjs application.

const result = await axios.post('localhost:8081/application', payload);

Is there anyone who can provide guidance on resolving this CORS issue?

Answer №1

The middleware known as cors provides the flexibility to define specific options for passing through. For instance:

 {
      "origin": "http://example.com",
      "credentials": true,
  }

It's worth mentioning that 'origin' can also accept an array of origins that you want to allow, and your request must include:

 {
     credentials: 'include',
 }

This is crucial in ensuring the cookies are appropriately sent with the requests.

I trust this information proves beneficial...

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

Error 500: The listener parameter must be a function when using ServerResponse.addListener

After reading the answer on this post events.js:130 throw TypeError('listener must be a function') I have been working on setting up a Logging system where every action is saved in the database. I wanted to listen for the finish or close event o ...

What is the reason for Jest attempting to resolve all components in my index.ts file?

Having a bit of trouble while using Jest (with Enzyme) to test my Typescript-React project due to an issue with an alias module. The module is being found correctly, but I believe the problem may lie in the structure of one of my files. In my jest.config ...

Managing nested dependencies through npm

Seeking advice on effectively managing nested dependencies in npm. My current scenario involves running an app with express.js and express-mongostore in a nodeenv environment. Due to nodeenv, I have opted to globally npm all packages, leading them to be s ...

Sort by user identifier

I'm having an issue trying to filter a list of posts and comments by userId. I've passed the userId params as postCreator and commentCreator, but something seems to be amiss. Can anyone help me identify what I might be doing wrong? // Defining ...

The provided argument, which is of type 'RefObject<HTMLDivElement>', cannot be assigned to the parameter of type 'IDivPosition'

Currently, I am implementing Typescript with React. To organize my code, I've created a separate file for my custom function called DivPosition.tsx. In this setup, I am utilizing useRef to pass the reference of the div element to my function. However ...

Has an official Typescript declaration file been created for fabric.js?

Currently, I have come across a Typescript definition for fabric.js on https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/fabric (https://www.npmjs.com/package/@types/fabric). However, its official status is unclear. Does anyone have more ...

The node module.exports in promise function may result in an undefined return value

When attempting to log the Promise in routes.js, it returns as undefined. However, if logged in queries.js, it works fine. What changes should be made to the promise in order to properly return a response to routes.js? In queries.js: const rsClient = req ...

Postman post request failing to insert Mongoose model keys

Recently, I've been experimenting with the post method below to generate new documents. However, when I submit a post request in Postman (for example http://localhost:3000/api/posts?title=HeaderThree), a new document is indeed created, but unfortunate ...

What is the process for declaring a set in typescript?

In the documentation on basic types for Typescript, it explains using Arrays as a primitive type I am interested in the syntax: const numbers: string[] = [] How can I achieve the same with a set? ...

What issue are we encountering with those `if` statements?

I am facing an issue with my Angular component code. Here is the code snippet: i=18; onScrollDown(evt:any) { setTimeout(()=>{ console.log(this.i) this.api.getApi().subscribe(({tool,beuty}) => { if (evt.index == ...

Checking JavaScript files with TSLint

After spending many hours attempting to make this work, I still haven't had any success... I am wondering: How can I utilize TSLint for a .js file? The reason behind this is my effort to create the best possible IDE for developing numerous JavaScrip ...

Tsyringe - Utilizing Dependency Injection with Multiple Constructors

Hey there, how's everyone doing today? I'm venturing into something new and different, stepping slightly away from the usual concept but aiming to accomplish my goal in a more refined manner. Currently, I am utilizing a repository pattern and l ...

The search for 'Renderer2' in '@angular/core' did not yield any results

After successfully installing Angular Material in my Angular Project by following the instructions provided in the Material documentation, I encountered some issues. Specifically, when attempting to launch the application with 'npm start', I star ...

Check out the attributes of a class

I have a TypeScript class that is defined like this: export class MyModel { ID: number; TYPE_ID: number; RECOMMENDED_HOURS: number; UNASSIGNED_HOURS: number; } In a different .ts file, I instantiate this class within a component: export class My ...

Unacceptable POST Request Inputs

I'm encountering an issue with invalid inputs while making a signup POST request in Postman. I have reviewed my User Model attributes but I am unable to identify which input(s) are causing the error. Below you will find details of my model, controller ...

The process of passing a variable between two routes in an Express application

Is there a method to pass variables between two routes in expressJS without setting it as a global variable? For example, if we have the following routes: exports.routeOne = (req,res) => { var myVariable='this is the variable to be shared'; ...

Leverage glob patterns within TypeScript declaration files

Utilizing the file-loader webpack plugin allows for the conversion of media imports into their URLs. For example, in import src from './image.png', the variable src is treated as a string. To inform TypeScript about this behavior, one can create ...

A straightforward redirection in Express involving a static file

Just starting out with Node and Express and encountering a bit of trouble. I have a static html page where users enter their username via ajax to my server, and then I want to redirect them to another html file. const express = require("express"); const b ...

What are the steps to modify the authorization header of an HTTP GET request sent from a hyperlink <a href> element?

I have a unique Angular application that securely saves JWT tokens in localstorage for authentication purposes. Now, I am eager to explore how to extract this JWT token and embed it into an HTTP GET request that opens up as a fresh web page instead of disp ...

Display a semantic-ui-react popup in React utilizing Typescript, without the need for a button or anchor tag to trigger it

Is there a way to trigger a popup that displays "No Data Found" if the backend API returns no data? I've been trying to implement this feature without success. Any assistance would be greatly appreciated. I'm currently making a fetch call to retr ...