0

I am trying to send the form data to backend MongoDB using Axios. The API is working fine if post request is sent from postman, but fails to hit the API if request comes from the frontend. I have attached the screenshot of the error:

Error ss

Code of frontend:

    const res = await axios.post('http://localhost:8000/api/users/adduser', {
      name: name,
      email: email,
      phone: phone,
      message: message
    })
    .then(function (response) {
      console.log(response);
    })
    .catch(function (error) {
      console.log(error);
    });
  }

Backend code: (Node.js)

//ADD USER
router.post("/adduser", async(req, res) => {
    console.log("add-user api");
    try{
        console.log(req.body);
        let newUser = new User({
            id: Date.now().toString(36),
            name: req.body.name,
            email: req.body.email,
            phone: req.body.phone,
            message: req.body.message
        });
        const user = await newUser.save();
        res.status(200).json(user);
    }catch(err){
        res.status(500).json(err);
    }
});

index.js:

const express = require("express");
const app = express();
const dotenv = require("dotenv")  
const mongoose = require("mongoose")

//Models
require('./models/User')
//Routes
const userRoute = require("./routes/users")

dotenv.config();
//A middleware which will Extract req.body for us
app.use(express.json());

mongoose.set("strictQuery", true);
mongoose.connect(process.env.MONGO_URL, {
    useNewUrlParser:true,
    useUnifiedTopology: true,
})
.then(console.log("Connected to MongoDB"))
.catch(err => console.log(err));

app.use("/api/users", userRoute);

app.listen(8000, () => {
    console.log(`Server is running on port 8000.`);
  });
jub0bs
  • 60,866
  • 25
  • 183
  • 186
  • Read https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS and then use https://expressjs.com/en/resources/middleware/cors.html and configure it according to your needs. – jub0bs Jan 08 '23 at 16:08
  • That middleware's default configuration should suit your needs. Add `const cors = require('cors');` and `app.use(cors());` at the top. – jub0bs Jan 08 '23 at 16:29
  • Does this answer your question? [How to enable cors nodejs with express?](https://stackoverflow.com/questions/43150051/how-to-enable-cors-nodejs-with-express) – bogdanoff Jan 08 '23 at 16:44

2 Answers2

0

use instead cors npm package and then get advantages of app.use(cors()), this will allow all origins to access your content.

If you want to allow only some origins for security purposes : see the docs on npm here

-1

There are 2 options to fix the cors issue from backend

1. By using cors Nodejs Package**

cors package is use to provide a middleware that can be used to enable CORS with various options.

Follow these steps: a.npm i cors b. import cors in your main file (index.js) const cors = require("cors") c. and app.use(cors())

2. Without package

app.use(function (req, res, next) {
  res.get("X-Frame-Options")
  res.header("Access-Control-Allow-Origin", "*")
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization")
  res.header("Access-Control-Allow-Methods", "PUT, POST, GET, DELETE, OPTIONS")
)
})
Mandeep
  • 364
  • 2
  • 16