快速用node.js写接口

377 阅读3分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路

node.js写接口

配置

安装

  1. 自己官网安装

  2. 查看安装后环境对不对

打开cmd命令输入path查看有没有node js的配置路径,如果没有自己配置可以参考环境变量配置

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-KD9T5SC3-1629905928786)(C:\Users\Lenovo\AppData\Roaming\Typora\typora-user-images\image-20210824233751993.png)]

你也可以选择手动打开环境变量查看是不是已经自动配好了

  1. 进入你安装node的路径输入

    node-version(或者node -v)查看安装版本

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-eSMrdO7j-1629905928791)(C:\Users\Lenovo\AppData\Roaming\Typora\typora-user-images\image-20210824234117644.png)]

查看安装了npm没有

输入npm-version(npm -v)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-EKMSkpLG-1629905928793)(C:\Users\Lenovo\AppData\Roaming\Typora\typora-user-images\image-20210824234242283.png)]

npm初始化

输入npm init

然后下面的文件信息可以按照自己的选择修改或是直接回车默认选项

如果出现下面这个bug:

npm ERR! code EPERM npm ERR! syscall open npm ERR! path F:\node\package.json npm ERR! errno -4048 npm ERR! Error: EPERM: operation not permitted, open 'F:\node\package.json' npm ERR! [Error: EPERM: operation not permitted, open 'F:\node\package.json'] { npm ERR! errno: -4048, npm ERR! code: 'EPERM', npm ERR! syscall: 'open', npm ERR! path: 'F:\node\package.json' npm ERR! } npm ERR! npm ERR! The operation was rejected by your operating system. npm ERR! It's possible that the file was already in use (by a text editor or antivirus), npm ERR! or that you lack permissions to access it. npm ERR! npm ERR! If you believe this might be a permissions issue, please double-check the npm ERR! permissions of the file and its containing directories, or try running npm ERR! the command again as root/Administrator.

npm ERR! A complete log of this run can be found in: npm ERR! C:\Users\Lenovo\AppData\Local\npm-cache_logs\2021-08-24T15_55_49_654Z-debug.log

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-sA9qRqDl-1629905928797)(C:\Users\Lenovo\AppData\Roaming\Typora\typora-user-images\image-20210824235832055.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-z61pSFlT-1629905928799)(C:\Users\Lenovo\AppData\Roaming\Typora\typora-user-images\image-20210825000019706.png)]

可能是你没有以管理员权限打开cmd命令行

重新再来

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-h8Xegpga-1629905928802)(C:\Users\Lenovo\AppData\Roaming\Typora\typora-user-images\image-20210825000254840.png)]

就好啦!

添加express

npm install express --no-save

添加成功后我们就可以进行一个小案例的编写啦!

案例运行

新建一个js文件

  1. 初始化

    • mkdir XXX(在当前目录下创建一个夹)

    • cd XXX进入你创建的这个夹

    • yarn init -y

    • yarn add express

  2. 编写代码

const express = require("express");

const app = express();

// 端口号,loclahost代表本机地址

const port = 3000;

app.get("/", (req, res) => {

 res.send("hello world");

})

app.listen(port, () => {

​ console.log(Express server listening at http://localhost:${port});

 })

 // 下面我们开始处理url请求以及路由配置,让它可以跑起来

3. 运行

终端敲一个 node XXX.js

image-20210825233723483

  1. 查看效果

点开这个链接

image-20210825233755049

我们的请求就发送成功啦!!!

[外链图片转存中...(img-PpP0g3n6-1629905928804)]

  1. 查看效果

点开这个链接

[外链图片转存中...(img-PCKhDmX7-1629905928805)]

我们的请求就发送成功啦!!!