You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用Express接口时遭CORS策略阻止XMLHttpRequest请求问题

解决CORS策略阻止XMLHttpRequest请求的问题

我写了一个前端页面,点击Convert按钮会触发convertTTS函数,通过XMLHttpRequest请求本地localhost:5500/convertTextToMp3接口;后端用Node.js+Express实现,接口会调用myFunction并返回响应。原本预期前端控制台会打印'It works!',但实际出现了Access to XMLHttpRequest has been blocked by CORS policy错误。

前端代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    
    <input type="text" id="textInput">
    <button id="convertButton" onclick="convertTTS()">Convert</button>

    <script>
        function convertTTS() {
            // Creating Our XMLHttpRequest object 
            var url = 'localhost:5500/convertTextToMp3/';
            var xhttp = new XMLHttpRequest();

            // Making our connection  
            xhttp.open("GET", url, true);

            // function execute after request ist successful
            xhttp.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                    console.log("It works!");
                }
            };

            // Sending our request
            xhttp.send();
        }
    </script>
</body>
</html>

后端代码

require("dotenv").config();
const express = require('express');
const app = express();

function myFunction() {
    console.log("My function!");
}

app.get('/convertTextToMp3', (req, res) => {
    myFunction();
    res.send('Function called successfully!');
});

app.listen(5500, () => console.log('Server started on port 5500'));

问题原因及解决方法

原因

浏览器的同源策略(CORS)会阻止跨域请求——只要前端页面的运行域名/端口和后端接口的不一致,就会触发这个限制。另外前端请求的URL还缺少协议头,也是潜在问题。

解决步骤

  1. 修复前端请求URL
    给URL加上http://协议头,同时去掉末尾多余的斜杠,和后端接口路径保持一致:

    var url = 'http://localhost:5500/convertTextToMp3';
    
  2. 后端配置CORS
    在Express项目中安装并启用cors中间件,允许前端的跨域请求:

    • 先安装依赖:
      npm install cors
      
    • 修改后端代码,引入并使用cors:
      require("dotenv").config();
      const express = require('express');
      const cors = require('cors');
      const app = express();
      
      // 全局启用CORS,允许所有源的请求
      app.use(cors());
      
      function myFunction() {
          console.log("My function!");
      }
      
      app.get('/convertTextToMp3', (req, res) => {
          myFunction();
          res.send('Function called successfully!');
      });
      
      app.listen(5500, () => console.log('Server started on port 5500'));
      

可选优化

如果不想全局开放CORS,可以只给特定接口配置,或者限制允许的来源:

  • 仅给目标接口启用CORS:
    app.get('/convertTextToMp3', cors(), (req, res) => {
        myFunction();
        res.send('Function called successfully!');
    });
    
  • 限制仅特定来源可访问:
    const corsOptions = {
        origin: 'http://localhost:8080' // 替换为前端实际运行的地址
    };
    app.use(cors(corsOptions));
    

内容的提问来源于stack exchange,提问作者Userx10xC

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 18:06:39