简体   繁体   中英

How to solve CORS error in React and Node/Express

I am using React in the frontend and node/express server in the backend and the project worked fine before but now i am getting a CORS error

Access to fetch at 'https://dry-reef-22080.herokuapp.com/imageUrl' from origin 'https://smart-brain-04.herokuapp.com' has been blocked by CORS policy: 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 tried adding the mode and headers in the frontend

fetch(`https://dry-reef-22080.herokuapp.com/imageUrl`, {
      method: "post",
      mode: "no-cors",
      headers: {
        "Access-Control-Allow-Origin": "*",
        "Content-type": "application/json"
      },
      body: JSON.stringify({
        input: this.state.input
      })
    })

I access a another external api called clarifail in the backend

const Clarifai = require('clarifai');

const app = new Clarifai.App({
    apiKey: 'XYZ'
   });

const handleImageUrl = (req, res) => {
   app.models.predict(
    'c0c0ac362b03416da06ab3fa36fb58e3',
    req.body.input)
    .then(data => {
        res.json(data);
    })
   }

i also tried to use the npm package cors but the problem still persists

const express = require('express');
const bcrypt = require('bcrypt-nodejs');
const cors = require('cors');
const knex = require('knex');

const Register = require('./Controllers/Register');
const signin = require('./Controllers/signin');
const profileget = require('./Controllers/profileget');
const image = require('./Controllers/image');

process.env.NODE_TLS_REJECT_UNAUTHORIZED = 0

const db = knex({
    client: 'pg',
    connection: {
      connectionString: process.env.DATABASE_URL,
      ssl: true
    }
  });

const app = express();

app.use(cors())
app.use(express.json());

Try this set the mode from fetch to cors, since you are using the cors npm module in your backend you should also use cors for your request going to the backend. It should look somewhat like this:

fetch(`https://dry-reef-22080.herokuapp.com/imageUrl`, {
  method: "post",
  mode: "cors",
  headers: {
    "Content-type": "application/json"
  },
  body: JSON.stringify({
    input: this.state.input
  })
})

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