skip to Main Content

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.`);
  });

2

Answers


  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")
    )
    })
    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search