简体   繁体   中英

Getting cors error in react (even after installing and importing cors) in backend

i am getting cross origin request blocked error in react i have installed cors in the backend i have also done require cors but still getting the same error

ProductState.js (localhost:3000)

//ROUTE:2 - Add a product using Post "api/products/addproduct" Login required
router.post('/addproducts', fetchuser, [
    body('title', 'Enter the title').isLength({ min: 4 }),
    body('description').isLength({ min: 10 }),
    body('price', "Must be in Rupee per KG")
    // res.json([])
], async (req, res) => {
    try {

        const { title, description, imgURL, price } = req.body;
        //if there are errors, return bad requests and the error
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            return res.status(400).json({ errors: errors.array() });
        }

        const product = new Product({
            title, description, imgURL, price, user: req.user.id
        })
        const savedProduct = await product.save();
        res.json(savedProduct);
    } catch (error) {
        console.error(error.message);
        res.status(500).json.send("Internal server error occurred");
    }
})

index.js (localhost:2000 Backend)

const connectToMongo = require('./db.js');
const express = require('express');
var cors = require('cors')



connectToMongo();
const app = express(); 
const port = 2000;


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


//Available Routes
app.use('/api/auth', require('./routes/auth'));
app.use('/api/products', require('./routes/products'));



  
app.get('/', (req, res) => {
  res.send('Hello World!')
})

app.listen(port, () => {
  console.log(`E-Bazar listening  on port ${port}`)
})

Package.json (localhost:2000 Backend)

{
  "name": "theebazaar-backend",
  "version": "1.0.0",
  "description": "backend for the TheEBazaar - using MERN Stack",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "bcryptjs": "^2.4.3",
    "cors": "^2.8.5",
    "express": "^4.18.2",
    "express-validator": "^6.14.2",
    "jsonwebtoken": "^8.5.1",
    "mongoose": "^6.8.0"
  },
  "devDependencies": {
    "nodemon": "^2.0.20"
  }
}

i tried installing cors and importing cors in the backend directory but it didn't help

You can configure cors option using corsOptions object

const cors = require('cors');
var corsOptions = {
    origin: '*',
    optionsSuccessStatus: 200,
}
app.use(cors(corsOptions));

However allowing all origins ('*') might cause some security issues, if you really don't want to allow all origins to access your resources you can specify origins in the same property:

origin: 'http://example1.com', // Use array for multiple origins

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