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

如何在ReactJS中使用json-server?启动脚本执行被禁用问题咨询

问题原因与解决方案

一、启动json-server失败的原因及修复方法

这个错误是Windows PowerShell的执行策略限制导致的。默认情况下,Windows为了系统安全,会阻止运行未经过数字签名的脚本文件,而json-server启动时会调用相关脚本,刚好触发了这个安全限制。

修复方法很简单:

  1. 以管理员身份打开PowerShell
  2. 执行以下命令修改执行策略:
    Set-ExecutionPolicy RemoteSigned
    
  3. 出现确认提示时输入Y并回车

这个策略允许运行本地创建的脚本,同时对从网上下载的脚本要求签名,既解决了当前问题又保持了基本的安全性。如果之后想恢复默认的严格策略,执行Set-ExecutionPolicy Restricted即可。

二、在ReactJS中使用json-server的完整步骤

下面是一套落地性强的流程,帮你在React项目里快速用上json-server模拟后端接口:

1. 安装json-server

如果你还没全局安装,执行:

npm install -g json-server

如果是团队协作项目,更推荐安装到项目本地依赖(避免环境不一致):

npm install json-server --save-dev

2. 准备数据文件

在项目根目录创建db.json,内容可沿用你之前的配置(格式化后更易维护):

{
  "employees": [
    { "id": 1, "first_name": "Sebastian", "last_name": "Eschweiler", "email": "sebastian@codingthesmartway.com" },
    { "id": 2, "first_name": "Steve", "last_name": "Palmer", "email": "steve@codingthesmartway.com" },
    { "id": 3, "first_name": "Ann", "last_name": "Smith", "email": "ann@codingthesmartway.com" }
  ]
}

3. 启动json-server服务

  • 若为全局安装,直接在项目根目录执行(指定端口避免和React默认的3000端口冲突):
    json-server --watch db.json --port 5000
    
  • 若为本地安装,在package.json的scripts中添加启动命令:
    "scripts": {
      "start": "react-scripts start",
      "server": "json-server --watch db.json --port 5000",
      // 其他原有脚本...
    }
    
    之后执行npm run server即可启动服务。

4. 在React组件中请求数据

你可以用原生fetch或者axios请求接口,这里分别给出示例:

用原生fetch的示例组件

import { useState, useEffect } from 'react';

function EmployeeList() {
  const [employees, setEmployees] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch('http://localhost:5000/employees')
      .then(response => response.json())
      .then(data => {
        setEmployees(data);
        setLoading(false);
      })
      .catch(error => console.error('获取员工数据失败:', error));
  }, []);

  if (loading) return <div>加载中...</div>;

  return (
    <div className="employee-list">
      <h2>员工列表</h2>
      <ul>
        {employees.map(emp => (
          <li key={emp.id}>
            {emp.first_name} {emp.last_name} - {emp.email}
          </li>
        ))}
      </ul>
    </div>
  );
}

export default EmployeeList;

用axios的示例组件

先安装axios:

npm install axios

再修改请求逻辑:

import { useState, useEffect } from 'react';
import axios from 'axios';

function EmployeeList() {
  const [employees, setEmployees] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    axios.get('http://localhost:5000/employees')
      .then(response => {
        setEmployees(response.data);
        setLoading(false);
      })
      .catch(error => console.error('获取员工数据失败:', error));
  }, []);

  if (loading) return <div>加载中...</div>;

  return (
    <div className="employee-list">
      <h2>员工列表</h2>
      <ul>
        {employees.map(emp => (
          <li key={emp.id}>
            {emp.first_name} {emp.last_name} - {emp.email}
          </li>
        ))}
      </ul>
    </div>
  );
}

export default EmployeeList;

除了GET请求,json-server还支持POST、PUT、DELETE等常用RESTful请求,完全能覆盖前端开发时的接口模拟需求。

内容的提问来源于stack exchange,提问作者Khoa Võ Đức

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 20:58:11