1. First of all, confirm whether the node environment is normally installed on your computer
How to confirm?
Open the console, enter node -v
node -v
As shown in the screenshot below, it means that the node environment has been installed
If the node command is not found, please move to Baidu by yourself, download and install the node environment
2. Create a new folder, let’s first default the folder name to express-demo
Next, add a package.json file under this folder
The content of the file is as follows
{
"name": "test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1"
}
}
After saving the file, open the console under the root path of the folder, enter npm i, and press Enter
npm i
After a short wait for the dependency package to be installed, you will find a new node_modules folder in the project directory, which means that the dependency has been installed successfully at this time
3. Create a new server.js file under the project root path, the content of the file is as follows
const express = require("express");
const app = express();
// 设置允许跨域访问
app.all("*", function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Credentials", true);
res.header(
"Access-Control-Allow-Headers",
"Content-Type,Content-Length, Authorization, Accept,X-Requested-With"
);
res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
res.header("Content-Type", "application/json;charset=utf-8");
next();
});
const data = {
code: 200,
data: "hello world",
msg: "请求成功",
};
const testApi = "/api/test";
app.get(testApi, (req, res) => {
res.send(data);
});
//配置服务端口
const baseUrl = "192.168.1.9"; // 本机IP
const port = 8088; // 端口号
app.server = app.listen(port, baseUrl, () => {
console.log(`${baseUrl}:${port}${testApi}`);
});
Remarks, the local ip written in the appeal code is the author’s local computer ip. If you want to check your computer’s ip, you can ctrl+ R and enter cmd to open the console and enter ipconfig to view
ipconfig
The ip address will appear in this place in the figure below, just copy it out
4. After editing the server.js, at this time we open the console under the project root path and enter node server.js
node server.js
The console outputs the following prompt, indicating that the execution is successful
5. Finally we open the browser, copy the input result of the console to the address bar and visit
If you get to this step smoothly, congratulations on your success in creating a new interface.
1618bbdabd2e82 Incidentally, if you modify the content of the server.js file in the future, you need to ! ! Remember
The above is just a simple example, follow-up changes should be considered according to your actual needs.
Okay, let's share it here this time.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。