Node cross-domain Node static page Deploy vercel express modular development Use node.js to simply build web services Use node to simply build back-end services Use node to build services Deploy Vercel Deploy vercel express modular development
- 1. Initialize project
- 2. Install the Express.js web service framework
- 3. Create the app.js main entry file and implement GET and POST requests
- 4. Start the service
- 5. Request a test
- 6. Interfaces are divided into modules according to routing
- 7. Cross-domain settings
- 8. Static page processing
- 8. Deploy vercel
- 10. Complete Demo code address
1. Initialization project
For example, the project name is node-server-demo
mkdir node-server-demo
Enter the node-server-demo
folder and initialize the package.json
file
cd node-server-demo
Initialize the package.json
file
npm init -y
2. Install Express.js Web service framework
npm install express
3. Create the app.js main entry file and implement GET and POST requests
const express = require('express'); const app = express(); // Service port number const port = 8080; app.use(express.json()); // Process GET request / Return hello app.get('/', (req, res) => {<!-- --> res.send('hello'); }); // Process GET request /get, parameter a, and return a parameter value app.get('/get', (req, res) => {<!-- --> const {<!-- --> a } = req.query; res.send(a); }); // Handle POST request /post, accept JSON parameters and return the same JSON parameters app.post('/post', (req, res) => {<!-- --> const jsonData = req.body; res.json(jsonData); }); app.listen(port, () => {<!-- --> console.log(`node service has been started. The port number is: ${<!-- -->port}`); });
4. Start the service
node app.js
5. Request test
To request a test, use postman or apifox
GET
request
POST
request
At this point, node simply builds the server and completes it.
6. Interfaces are divided into modules according to routing
All interfaces written in app.js are difficult to maintain and bloated. Actual development must be divided into modules.
Assume there are two routing modules:
appRouter.js
specifically handles app-side interface servicesadminRouter.js
specifically handles admin-side interface services
Create router
folder to store corresponding routing files
appRouter.js
Routing file content
//This routing file mainly handles app-side interface services const express = require('express'); const app = express.Router(); app.get('/login', (req, res) => {<!-- --> res.send('App request login') }); //Export routing module module.exports = app
adminRouter.js
Routing file content
//This routing file mainly handles the admin side interface service const express = require('express'); const admin = express.Router(); admin.get('/login', (req, res) => {<!-- --> res.send('Admin side requests login') }); //Export routing module module.exports=admin
At this time, the file directory comparison:
Register routing in the main entry of app.js
const express = require('express'); //Introduce external routing files const appRouter = require('./router/appRouter') const adminRouter = require('./router/adminRouter') const app = express(); const port = 8080; app.use(express.json()); //Register the route. To access the registered routing module interface, you need to add the prefix of the registered route. app.use('/app', appRouter) app.use('/admin', adminRouter) // Process GET request / Return hello app.get('/', (req, res) => {<!-- --> res.send('hello'); }); // Process GET request /get, parameter a, and return a parameter value app.get('/get', (req, res) => {<!-- --> const {<!-- --> a } = req.query; res.send(a); }); // Handle POST request /post, accept JSON parameters and return the same JSON parameters app.post('/post', (req, res) => {<!-- --> const jsonData = req.body; res.json(jsonData); }); app.listen(port, () => {<!-- --> console.log(`node service has been started. The port number is: ${<!-- -->port}`); });
Start the test and visit /app
, /admin
. You can see that both of them have taken effect.
7. Cross-domain settings
Install cross-domain plug-in official documentation
npm install cors
Referenced in app.js
, it should be noted here that the app.use()
code must be placed below require()
, otherwise it may appear It does not take effect. You should also pay attention when using other plug-ins.
// Cross-domain support official documentation: https://github.com/expressjs/cors const cors = require('cors') // Enable all requests to support cross-domain app.use(cors())
8. Static page processing
Create a public
or src
directory folder. You can name it whatever you want. I put the html file here under public/pages/
The file structure at this time:
Write a route to access index.html
. The diagram here is simple and direct. The root route of /
in app.js
accesses index.html.
file is also more reasonable.
//process / root request app.get('/', (req, res) => {<!-- --> const filePath = __dirname + '/public/pages/index.html'; res.sendFile(filePath); });
Complete app.js
const express = require('express'); //Introduce external routing files const appRouter = require('./router/appRouter') const adminRouter = require('./router/adminRouter') const app = express(); const port = 8080; app.use(express.json()); //Register the route. To access the registered routing module interface, you need to add the prefix of the registered route. app.use('/app', appRouter) app.use('/admin', adminRouter) // Handle / root request app.get('/', (req, res) => {<!-- --> const filePath = __dirname + '/public/pages/index.html'; res.sendFile(filePath); }); // Process GET request /get, parameter a, and return a parameter value app.get('/get', (req, res) => {<!-- --> const {<!-- --> a } = req.query; res.send(a); }); // Handle POST request /post, accept JSON parameters and return the same JSON parameters app.post('/post', (req, res) => {<!-- --> const jsonData = req.body; res.json(jsonData); }); app.listen(port, () => {<!-- --> console.log(`node service has been started. The port number is: ${<!-- -->port}`); });
Visit /
and the test has taken effect.
8. Deploy vercel
First you need to prepare a Vercel account, which I won’t explain here.
Install Vercel scaffolding globally on your computer
npm install -g vercel
Login to Vercel
vercel login
Create the vercel.json
file in the root directory of the node.js
project. The content of this file is basically fixed. If 404 occurs during deployment, please check /app or /admin
Is the routing registration normal?
{<!-- --> "version": 2, "builds": [ {<!-- --> "src": "app.js", "use": "@vercel/node" } ], "routes": [ {<!-- --> "src": "/(.*)", "dest": "app.js" } ] }
Directory structure at this time:
To deploy the preview of the current project to Vercel, execute the following command in the root directory of the node.js project. After the deployment is completed, a preview address and deployment address will be given.
vercel
Deploy the current project preview to the Vercel formal environment. Execute the following command in the root directory of the node.js project. After the deployment is completed, a formal address and deployment address will be given.
vercel --prod
The content ends here
10. Complete Demo code address
Attached demo address