Home > front end >  Cors error strict-origin-when-cross-origin simple nodeJS-reactJS project
Cors error strict-origin-when-cross-origin simple nodeJS-reactJS project

Time:11-24

I'm trying to upload image to Cloundinary, but an error occurred with status code 500 relating to cors though i had set the server to allow all origin.

The error message is:

POST http://localhost:5000/my-route-upload 500 (Internal Server Error)

here is my POST function :

const cloudinaryUpload = (fileToUpload) => {
    return axios.post(API_URL   '/cloudinary-upload', fileToUpload)
    .then(res => console.log(res))
    .catch(err => {
        console.log(err)
        console.log("cannot post")
    }); }

In server side, I had added the following block in App.JS

const cors = require('cors'); 
var app = express();
app.use(cors({
  origin: "*",
  })
);

Those codes did execute, i tried modify the origin to the specific one like http://127.0.0.1:3001 (my client port is 3000). Then it came out another error message

Back to the first error, in tab Network/Headers :

Request URL: http://localhost:5000/cloudinary-upload
Request Method: POST
Status Code: 500 
Referrer Policy: strict-origin-when-cross-origin

Access-Control-Allow-Origin: *

Host: localhost:5000
Origin: http://127.0.0.1:3000

I don't know why it didn't work. I use create-react-app for client and Express generator for server

CodePudding user response:

Maybe you should add the content-type header to your Axios request. Like this.

const res = await axios.post('url', data, {
  headers: {
    'content-type': 'application/json'
  }
});

CodePudding user response:

Setup a proxy for your server from your client

Proxy can be a simple "proxy": "http://localhost:5000" in your package.json, where all unknown requests will be proxied to localhost:5000 Essentially you need to call the api from client as /my-route-upload instead of http://localhost:5000/my-route-upload.

But preferred method would be to add a file called src/setupProxy.js and $ npm install http-proxy-middleware --save add this to the file


module.exports = function(app) {
  app.use(
    '/api',
    createProxyMiddleware({
      target: 'http://localhost:5000',
      changeOrigin: true,
    })
  );
};```

Also look at enabling cors in express
https://enable-cors.org/server_expressjs.html
  • Related