The requested resource does not contain the 'Access-Control-Allow-Origin' header. It has already been included in the headers

Despite adding the 'Access-Control-Allow-Origin': '*' header to my Axios request, I am still encountering the same error.

When trying to access 'http://backendUrlEndPoint' from origin 'https://frontendURL', the CORS policy blocks the request: The preflight response does not satisfy the access control check because there is no 'Access-Control-Allow-Origin' header present on the requested resource.

I have implemented cors as my middleware in the express server.

const cors = require("cors");
app.use(cors());

I am utilizing Axios for making API calls

const onClickHandler = async (e) => {
    e.preventDefault();
    try {
        const res = await axios.post("http://backendUrlEndPoint", userDetails, {
            headers: {
                "Content-Type": "application/json",
                "Access-Control-Allow-Origin": "*",
            },
        });
        console.log(res);
    } catch (err) {
        console.log(err);
    }
};

Answer №1

By utilizing this particular configuration, you can eliminate the need for providing a third argument in axios requests.

{
  headers: {
    "Content-Type": "application/json",
    "Access-Control-Allow-Origin": "*",
  }
}

It appears that there could be an issue on the server side. Implementing a basic server configuration seems to resolve any potential problems seamlessly.

const express = require("express");
const cors = require("cors");
const app = express();
app.use(cors());
app.post("/post", function (req, res) {
  res.json({ msg: "ok" });
});
app.listen(5000, () => {
  console.log('App listening at http://localhost:5000}');
});

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

Sending a link via email using Node.js and Express can be achieved by integrating nodemailer into

I need help with sending clickable links via email. Below is the code I am using: const data = { from: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bdd0d8fdcedcd0cdd1d8ce93d0dcd4d1dac8d393d2cfda">[email protec ...

What is the best way to enforce the image field as mandatory in a node.js application using postman?

If the image field is unchecked in Postman, I need to show an error message in response instead of a successful upload. How can this be achieved? Functionality of Multer const storage = multer.memoryStorage(); fileFilter = (req, file, cb, res) => { ...

Can Node.js handle parsing this as JSON?

Attempting to parse a small API that returns somewhat invalid JSON. Trying the following approach: var request = require('request'), url = 'urlhere'; request({ url: url }, function(error, response, body) { ...

The functionality to save user likes in React is not properly functioning on the like button

I created a like button in React that saves my choices, but it seems to be not saving the choices of other users. Additionally, it doesn't appear to restrict only authenticated users from marking likes. Can someone please help me identify what I' ...

Angular Material - Text currently not displaying

As a student at university, I recently decided to delve into Angular for my academic purposes. To ease myself in, I simply copied some material from the official Angular webpage and pasted it into my editor after using bower to install angular-material ("b ...

Retrieve the image URL from a Blue Prism Object Storage container by using a Node.js application

I currently have images stored in a container on my Object Storage instance in Bluemix. I am looking for a way to get the source URL for these images so that I can use them elsewhere. My plan is to create a Node.js application where I can make a post reque ...

How to Store Values from a ReadStream in an Array

I'm currently attempting to use a stream and the async/await keywords with the fast-csv library in order to read a CSV file synchronously. Unfortunately, the function I've written doesn't seem to be producing the expected output. My assumpt ...

NodeJS - leveraging forked processes on a single virtual machine with multiple processors versus the utilization of multiple virtual machines running a single process

In my NodeJS development project, I am working on a service that generates text files from images using a node wrapper for the tesseract OCR engine. The goal is to have this service running continuously, starting and restarting (in case of a crash) using u ...

What could be causing the multer middleware to fail to work properly?

Within the app.js file, there is a direct route to handle image uploads: app.post('/upload', upload.single('image'), (req, res) => { res.json({ message: 'pic uploaded' }); }); Posting to /upload successfully uploads the im ...

Steps to resolve the EEXIST error while setting up a reactjs project

I am a beginner in React and I am currently working on creating a new react app. However, I have encountered an issue during the process of creating this react-app. Any assistance would be greatly appreciated. npm ERR! code EEXIST npm ERR! path C:&bsol ...

Deploying Lambda projects on Amazon Web Services

Currently working on developing AWS Lambda functions for my project in Node.js, and I am now exploring the most efficient deployment method. My ideal approach would involve: Translating the ES7 code into a format that Lambda can interpret, potentially ut ...

The Route.get() function in Node.js is expecting a callback function, but instead received an unexpected object of type

Recently, I started coding with nodejs and express. In my file test.js located in the routes folder, I have written the following code: const express = require('express'); const router = new express.Router(); router.get('/test', (req ...

The structure of a project using a Vue app and a Node API

Seeking your thoughts on combining a Vue App with a Node using API for my upcoming project. I have set up two separate folders for the client (VueJs) and server (Node) locally: - client (VueJs) - server (Node) I am currently running them individually usi ...

What could be causing Express to display a different page than the one specified in res.render?

Upon trying to view the compare.ejs page, I encountered an unexpected issue where a different page was being rendered instead. What could be causing this discrepancy? Here is my app.js code: var compare = require('./routes/compare')(nav); app.u ...

Setting up a recurring task upon launching Express: How to Create a Scheduled Job

After starting to learn Express, I encountered an issue. My app is successfully serving a REST API, but I wanted to incorporate a scheduled job using node-schedule (https://www.npmjs.com/package/node-schedule). Here is how I set up this module: var schedu ...

Pass an array from a script file in JavaScript to index.js within the Express framework

I've encountered a challenge in sending an array (or JSON object) from script.js to index.js, my express server file. I've explored various solutions such as passing the variable through an HTML file and then to another JavaScript file, utilizing ...

What could be causing the user object's property in mongoose to appear as undefined?

This is my User Schema: var UserSchema = new Schema ({ username: String, password: String, nativeLanguage: { type: String, default: "English" }, The following route fetches a user object and prints it to the console. ro ...

Encountering difficulties with uploading upcoming project on a cpanel hosting due to an issue with the npm package

While attempting to upload my next project on a cpanel, I encountered an error during the installation of npm packages. npm ERR! code ERESOLVEnpm ERR! ERESOLVE unable to resolve dependency treenpm ERR! ERR! Found: <a href="/cdn-cgi/l/email-protection" c ...

What could be causing the nonsensical patterns to appear whenever I execute my node.js application code?

I am currently working on a pub-sub application using node.js, redis, and socket.io. Here is the code snippet I have for app.js on the server side: var express = require('express'); var app = express(); var redis = require('redis'); v ...

It is essential for npm to automatically install peer dependencies in the parent project without overlooking them

I am currently facing an issue with publishing a react application, let's call it project-A, as an npm package. This project has several dependencies like material-ui, dompurify, recharts, and more. In another application, project-B ...