0

Description:

I am trying to send JSON data from an HTML page to the Node.js server running locally on port 5000 using Fetch API.

Getting Error:

Access to fetch at 'http://localhost:5000/attend' from origin 'http://127.0.0.1:5501' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: 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.

port error:

POST http://localhost:5000/attend net::ERR_FAILED

Fetch error:

Uncaught (in promise) TypeError: Failed to fetch

Code Error Image

Node.js Code:

  connectdb();
    const app = express();
    
    app.use(express.static('public'));
    app.use(express.json({extended: false}));
    app.use (bodyParser.json());
    
    
    app.get('/',(req,res)=> res.send('API RUNNING'));
    
    app.post('/attend',async (req,res)=>{
        const {name,rollnumber} = req.body;
        console.log(name);
        console.log(rollnumber);
        try {
            let data = await Database.findOne({ rollnumber });
            if (data) {
                return res
                  .status(400)
                  .json({ errors: [{ msg: 'attandence is marked all ready' }] });
              }
              const  Data = new Database({
                rollnumber,
                name
              });
              await Data.save();
              res.json("added success fully");
        } catch (err) {
            console.error(err.message);
            res.status(500).send('Server Error');
        }
    });

HTML code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Marked</title>
    <link rel="stylesheet" href="/Client/style.css">
    <script>

     function attend(){
      const data = {
        name:'Syed Ali Shahzil',
        rollnumber:'180996'  
    };
    const options = {
      method:'POST',
      headers:{
        'Content-Type' : 'application/json;charset=UTF-8'
      },
      body: JSON.stringify(data)
    };
    fetch('http://localhost:5000/attend',options);  
    }
 
  
  
    </script>
</head>
<body>
    <div>
        <ul>
            <li><a  href="/">Home</a></li>
            <li><a class="active" href="marked.html">attendence Marked</a></li>
           
          </ul>
          <button class="button" onclick="attend()"> Present</button>
        </div>
</body>
</html>
1
  • 1
    Just to add some context to why this is happening: This CORS error is to be expected, because your origin domain (http://127.0.0.1:5501) does not match your destination domain (http://localhost:5000). Yes, 127.0.0.1 and localhost are synonymous, but even a difference in port number will trigger the error. See: Same Origin Policy Commented Jan 13, 2021 at 16:17

1 Answer 1

2

Do install the cors in your package by

$ npm install cors

And use it in your app

// Import cors
const cors = require("cors");
const app = express();

// Add it in the middleware
app.use(cors())
... Rest of your code

Your requests will work fine after that.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.