Used in the project express, simply use project

  • Express install
    npm install express --save-dv

It recommended to install the dev dependent inside

  • Install body-parse
    npm install body-parser --save-dev

When you submit a request data using the post method you might need rq.body to view the data you submit a request, but the body-parse is a middleware must install it, you can not install used to install

  • Src and create a sibling in the project server folder (the folder name easily take), then create a file in a folder index.js used to start express
const express = require('express')
// 新建app
const app = express()
const bodyParser = require('body-parser');//引入bodyParse中间件
app.use(bodyParser.json());//中间件的json数据解析功能
app.use(bodyParser.urlencoded({ extended: false }));//中间件的表单数据解析功能
//这里是设置跨域访问
app.all('*', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
  next();
});
//拦截get请求方法
app.get('/', function (req, res) {
  res.send('你好');
});
//拦截post请求方法
app.post('/request', function (req, res) {
  //console.log(req.body)//这里是打印接收到的请求数据,写不写随意,此时就用到bodyParse中间件
})
//监听的端口,自己可以定义,尽量使用express默认端口
app.listen(3000, function () {
  console.log('Node app start at port 3000')//这里是cmd打印出来你设置的端口
})
  • express start method

node server/index.jsThis is the file you just created folder and file names

Guess you like

Origin www.cnblogs.com/shiazhen/p/11985059.html