Home > Blockchain >  Request blocked by CORS-policy No 'Access-Control-Allow-Origin' when set header content-ty
Request blocked by CORS-policy No 'Access-Control-Allow-Origin' when set header content-ty

Time:11-20

I'm a newbie in react and nodeJS, and i have problem when i make request for update and insert data with image upload using multer, i send data as formData.

but, i getting error Request blocked by CORS while setting header content type multipart/form-data with dynamic request code, i have tried in postman and it works fine, and in other project also works perfect.

error :

Access to XMLHttpRequest at 'http://localhost:3000/v1/data/insert' from origin 'http://localhost:3001' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

here's the code

export async function put(url, data, config = {}) {
  return axiosApi
    .put(url, { ...data }, { ...config })
    .then(response => response.data)
}

export const updateProduct = data =>
  put(url.UPDATE_PRODUCT, data, {
    headers: {
      "content-type": "multipart/form-data",
    },
  })

API

app.use((req, res, next) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Method', 'GET, POST, PUT, PATCH, DELETE, OPTIONS');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
    next();
})

on another page I have tried to insert and update data but without uploading files or without sending content-type headers, can anyone help me please?

CodePudding user response:

You can use middleware providedby express

var express = require('express')
var cors = require('cors')
var app = express()

app.use(cors())

app.get('/products/:id', function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for all origins!'})
})

app.listen(80, function () {
  console.log('CORS-enabled web server listening on port 80')
})

docs for cors https://expressjs.com/en/resources/middleware/cors.html

CodePudding user response:

What web server are you using? Maybe Nginx, etc?. It would be for that you need to configure web server as well. you need to add this line to the server block in Nginx. doc

{
    location ~* \.(eot|ttf|woff|woff2)$ {
    add_header Access-Control-Allow-Origin *;
}

If you are using another webserver comment below

  • Related