Windows电脑上,想要启动一个JSON Server服务,但却启动失败。以下为发现问题和解决问题的过程。
一、全局安装
全局安装json-server
,使用命令:
npm i -g json-server
这里没有问题。
二、运行报错
然而运行命令:
json-server -v
会产生红色报错:
json-server : 无法加载文件 C:\Users\xxx\AppData\Roaming\npm\json-server.ps1,因为在此系统上禁止运行脚本。有关详细信息,请参阅 http
s:/go.microsoft.com/fwlink/?LinkID=135170 中的 about_Execution_Policies。
所在位置 行:1 字符: 1
+ json-server -v
+ ~~~~~~~~~~~
+ CategoryInfo : SecurityError: (:) [],PSSecurityException
+ FullyQualifiedErrorId : UnauthorizedAccess
三、原因分析
这跟操作系统有关,操作系统对当前用户没有设置运行脚本的权限。这个问题一般发生在重装系统或者新电脑等场景中。那么解决方法也就明确了,修改操作系统配置,使当前用户可以运行脚本。
四、解决方法
- 以管理员身份运行终端
- 打开powershell,注意不是cmd
- 查看当前用户权限(可选)
Get-ExecutionPolicy -List
此时结果如下:
Scope ExecutionPolicy
----- ---------------
MachinePolicy Undefined
UserPolicy Undefined
Process Undefined
CurrentUser Undefined
LocalMachine Undefined
- 修改用户权限
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser
此时再查看用户权限,结果如下:
Scope ExecutionPolicy
----- ---------------
MachinePolicy Undefined
UserPolicy Undefined
Process Undefined
CurrentUser RemoteSigned
LocalMachine Undefined
可以看到,当前用户权限已经配置成功。
五、验证结果
经过上述配置,当前用户已有权限。执行命令:
json-server --version
则会出现版本信息,而非红色报错。至此,问题解决。