The front end uses node to build a local environment

Use node.js to build a local service, and open the packaged code at the front end;

1. The express framework of node.js builds local services

1. Initialize the project

npm init

2. Install express

npm install express

If you see express and its corresponding version number in the dependencies of package.json, the installation is successful;

3. Create a new front folder and put the packaged front-end files in it;

4. Point out ./front as a static file in app.js

// 导入 express 模块
const express = require('express')
// 创建 express 的服务器实例
const app = express()
// 导入 cors 中间件
const cors = require('cors')
// 将 cors 注册为全局中间件
app.use(cors())
app.use(express.urlencoded({ extended: false }))



app.use("/", express.static("./front"))




// 调用 app.listen 方法,指定端口号并启动web服务器
app.listen(3007, function () {
    console.log('api server running at http://127.0.0.1:3007')
})

 5. Run the code && browser to open http://127.0.0.1:3007

node app.js

Attached:

To start a service with node, you need:

 node app.js

After modifying the server.js file, you need to stop the service (ctrl + c) and restart it to take effect;

With nodemon, there is no need to manually restart app.js frequently, because nodemon can monitor source code changes and automatically restart services. In this way, we only need to focus on writing code logic, without paying too much attention to services.

Install nodemon

(1) Run the following command to  nodemon install it as a globally available tool:

npm install -g nodemon

(2) Run the following command to check  nodemon whether the installation is successful:

nodemon -v

Guess you like

Origin blog.csdn.net/gsy445566778899/article/details/130263096