Giri Aakula
Giri Aakula

Reputation: 303

Unable to access API created on local node server

I created a simple API on a node server. The server is running on the port 9000. I created an endpoint called getUserDetails and I'm passing a simple object. The problem is I can access the API from the browser by entering the full URL 'http://localhost:9000/getUserDetails'.

But I cannot access the API in another HTML file. To elaborate, I created a simple HTML file to test out this API.

My node server:

const app = express();

app.get('/getUserDetails', (req, res) => {
    res.send({
        firstname : 'Giri',
        secondname: 'Aakula',
        dob: '15-09-1997',
        age: 22,
        qualification : 'Graduate',
        status : 'pass'
    })
})
app.listen(9000);

My HTML file

<!DOCTYPE html>
<html>
<head>
    <title>Test page</title>
    <style>
        h1{
            font-size: 50px;
        }
    </style>  
</head>
<script>
    fetch('http://localhost:9000/getUserDetails')
  .then(
    function(response) {
      if (response.status !== 200) {
        console.log('Looks like there was a problem. Status Code: ' +
          response.status);
        return;
      }

      // Examine the text in the response
      response.json().then(function(data) {
        console.log(data);
      });
    }
  )
  .catch(function(err) {
    console.log('Fetch Error :-S', err);
  });
</script>
<body>
    <h1>This is a test page</h1>
</body>
</html>

Upvotes: 0

Views: 69

Answers (1)

Giri Aakula
Giri Aakula

Reputation: 303

I forgot to add cors. By adding this one line fixed my issue.

const express = require('express');
const app = express();

app.get('/getUserDetails', (req, res) => {
    //this is the updated line
    res.setHeader('Access-Control-Allow-Origin', '*'); 

    res.send({
        firstname : 'Giri',
        secondname: 'Aakula',
        dob: '15-09-1997',
        age: 22,
        qualification : 'Graduate',
        status : 'pass'
    })
})
app.listen(9000);

Upvotes: 1

Related Questions