快速使用nodejs写接口

125 阅读2分钟

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

nodejs写接口

配置

安装

  1. 自己官网安装

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

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

image-20210824233751993

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

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

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

    image-20210824234117644

查看安装了npm没有

输入npm-version(npm -v)

image-20210824234242283

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

image-20210824235832055

image-20210825000019706

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

重新再来

image-20210825000254840

就好啦!

添加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

我们的请求就发送成功啦!!! 在这里插入图片描述4. 查看效果

点开这个链接

[外链图片转存中...(img-1Mq8YLeh-1629906230689)]

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