簡體   English   中英

無法訪問在本地節點服務器上創建的 API

[英]Unable to access API created on local node server

我在節點服務器上創建了一個簡單的 API。 服務器在端口 9000 上運行。我創建了一個名為 getUserDetails 的端點,並傳遞了一個簡單的對象。 問題是我可以通過輸入完整的 URL ' http://localhost:9000/getUserDetails ' 從瀏覽器訪問 API。

但我無法訪問另一個 HTML 文件中的 API。 為了詳細說明,我創建了一個簡單的 HTML 文件來測試這個 API。

我的節點服務器:

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);

我的 HTML 文件

<!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>

我忘了添加cors。 通過添加這一行解決了我的問題。

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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM