skip to Main Content

Profile.jsx

const res = await fetch(`http://localhost:5000/api/user/update/${currentUser._id}`, {
            method: "POST",
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify(formData)
        })

Error

Access to fetch at 'http://localhost:5000/api/user/update/651cce95aa88ef0726740018' from origin 'http://localhost:5173' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I am trying to call the API method that I defined on the backend server and has been blocked by cors policy. May I ask how to access the origin from the frontend in order to have two sides connected?

2

Answers


  1. The server should set Access-Control-Allow-Origin Header in the response (set it to ‘localhost’ or ‘*’).
    This is a security step to prevent phishing

    If this is not acceptable for you to set the header you can still use an extention to disble CORS on your browser, but notice this is only a development hack

    Login or Signup to reply.
  2. You can install CORS in your back-end side

    source: https://www.npmjs.com/package/cors

    var express = require('express')
    var cors = require('cors')
    var app = express()
     
    app.use(cors())
     
     
    app.listen(80, function () {
      console.log('CORS-enabled web server listening on port 80')
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search