简体   繁体   中英

Nodejs React CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource

i have got this error:

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

when my server cors options are:

app.use((req, res, next) => {
  res.header("Access-Control-Allow-Origin", "http://localhost:8081");
  res.header("Access-Control-Allow-Credentials", "true");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
  if (req.method === 'OPTIONS') {
      res.header("Access-Control-Allow-Methods", "PUT, POST, DELETE, GET");
      return res.status(200).json({});
  } 
  next();
});

And from the frontend i'm calling the server with this options:

var data = {
      image: imageCrop.current.getImage().toDataURL(),
      target: targetImage,
    }
    var config = {
      onUploadProgress: function (progressEvent) {
        var percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total)
        setUploadPercent(percentCompleted)
      },
      headers: authHeader(),
      withCredentials: true,
    }
    axios.post('uploadAvatar', data ,config).then((res) => {
      setUploadPercent(0);
      if (res.status === 200) {
        cogoToast.success("upload is completed")
        setUploadModal(false);
        upDateuserInfo();
      }
    }).catch((err) => {
      setUploadPercent(0);
      setUploadModal(false);
    });

The Auth header service is provided with:

export default function authHeader() {
  const user = JSON.parse(localStorage.getItem("user"));

  if (user && user.accessToken) {
    // For Spring Boot back-end
    // return { Authorization: "Bearer " + user.accessToken };
    // for Node.js Express back-end
    return { Authorization: "Bearer " + user.accessToken};
  } else {
    return {};
  }
}

What am i doing wrong?? please help me.., ps the call is working if i remove the image parameter and I can't set the "Access-Control-Allow-Origin","*" because it will give me an erro on using the wildcard.

i have resolved putting this line in package.json:

"proxy": "http://localhost:3000/api/"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM