【问题标题】:Cannot able to request the localhost node server with HTML page using fetch API无法使用 fetch API 请求带有 HTML 页面的 localhost 节点服务器
【发布时间】:2021-04-18 16:09:48
【问题描述】:

说明:

我正在尝试使用 Fetch API 将 JSON 数据从 HTML 页面发送到在端口 5000 上本地运行的 Node.js 服务器。

出现错误:

CORS 策略已阻止从源“http://127.0.0.1:5501”获取“http://localhost:5000/attend”的访问权限:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。

端口错误:

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

获取错误:

Uncaught (in promise) TypeError: Failed to fetch

Code Error Image

Node.js 代码:

  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 代码:

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

【问题讨论】:

  • 只是为了添加一些上下文来为什么会发生这种情况:这个 CORS 错误是意料之中的,因为您的源域 (http://127.0.0.1:5501) 与您的目标域不匹配 ( http://localhost:5000)。是的,127.0.0.1localhost 是同义词,但即使端口号不同也会触发错误。见:Same Origin Policy

标签: javascript html node.js express fetch-api


【解决方案1】:

请在你的包中安装cors

$ npm install cors

并在您的应用中使用它

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

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

之后您的请求将正常工作。

【讨论】:

    猜你喜欢
    • 2020-11-20
    • 2022-11-09
    • 1970-01-01
    • 1970-01-01
    • 2017-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多