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

如何本地运行Vue.js+System.js示例项目?解决CORS问题

如何本地运行无npm脚本的Vue.js/System.js项目并解决CORS错误

嘿,这个问题我熟!核心原因是浏览器的安全机制——直接用file://协议打开本地文件时,会触发CORS限制,哪怕是本地资源也不行。得用本地HTTP服务器来跑这个项目,下面给你一步步说操作:

运行前的准备操作

首先得确保你有Node.js(如果没装,去官网下个LTS版本就行,很简单),然后选一种方式启动本地HTTP服务器:

方式1:用http-server包(最推荐,简单快捷)

  • 打开终端,cd到你的项目根目录
  • 全局安装这个工具:npm install -g http-server
  • 启动服务器:http-server,终端会输出访问地址,一般是http://localhost:8080

方式2:用Python内置服务器(如果你已经装了Python)

  • 要是你装的Python 3,直接跑:python -m http.server 8080
  • 要是Python 2,跑这个:python -m SimpleHTTPServer 8080

方式3:用Node.js原生脚本(不用装额外包)

  • 在项目根目录新建个server.js文件,把下面的代码粘进去:
const http = require('http');
const fs = require('fs');
const path = require('path');

const server = http.createServer((req, res) => {
  let filePath = '.' + req.url;
  if (filePath === './') filePath = './index.html';

  const extname = path.extname(filePath);
  let contentType = 'text/html';
  switch (extname) {
    case '.js': contentType = 'text/javascript'; break;
    case '.css': contentType = 'text/css'; break;
    case '.json': contentType = 'application/json'; break;
  }

  fs.readFile(filePath, (error, content) => {
    if (error) {
      if(error.code === 'ENOENT'){
        res.writeHead(404);
        res.end('File not found');
      } else {
        res.writeHead(500);
        res.end('Server Error: ' + error.code);
      }
    } else {
      res.writeHead(200, { 'Content-Type': contentType });
      res.end(content, 'utf-8');
    }
  });
});

server.listen(8080, () => {
  console.log('Server running at http://localhost:8080/');
});
  • 然后在终端跑:node server.js

启动项目的步骤

  1. 确认你的index.html里的脚本路径都是相对路径(比如<script src="./system.js"></script>、<script src="./app/index.js"></script>这种,别用绝对路径)
  2. 启动上面任意一种服务器后,打开浏览器访问对应的地址(比如http://localhost:8080),这时候就能正常加载项目,不会再出现CORS错误了

额外小提示

  • 如果项目里缺依赖文件(比如System.js、Vue.js的本地文件),要么手动下载对应的版本放到项目对应目录,要么临时把脚本路径换成CDN地址也行
  • 等项目能正常跑起来后,要是想切换到Webpack,就可以先跑npm init -y初始化npm项目,然后装Webpack相关依赖,配置webpack.config.js来打包你的代码

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:49:55