Node.js write simple interface

Install Node.js

URL Download | Node.js Chinese Network

Create a new file to put the project, open the terminal in the file to initialize

npm init

install dependencies

  1. express —— Based on the node.js platform, a fast, open and minimal web development framework.
  2. body-parser - used to parse the form.
  3. mysql - relational database management system.
  4. cors - used to solve cross-domain problems.
npm install express body-parser mysql cors --save

Create a new file app.js in the file, introduce dependencies and start writing interfaces

Node.js needs to be re-run after the change

/* 引入express框架 */
const express = require('express');
const app = express();
/* 引入cors */
const cors = require('cors');
app.use(cors());
/* 引入body-parser */
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.all('*', function (req, res, next) {
  if (!req.get('Origin')) return next();
  // use "*" here to accept any origin
  res.set('Access-Control-Allow-Origin', '*');
  res.set('Access-Control-Allow-Methods', 'GET');
  res.set('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type');
  // res.set('Access-Control-Allow-Max-Age', 3600);
  if ('OPTIONS' == req.method) return res.send(200);
  next();
});

app.get('/', (req, res) => {
  res.send('<p style="color:red">服务已启动</p>');
})

app.get('/api/list', (req, res) => {
  res.json({
    code: 200,
    message: '成功',
    data: {
      list: [
		{
		id:'1',
	    name:'张三',
		gae:'18'
		},
		{
		id:'2',
		name:'李四',
		gae:'20'
		}
	  ]
    }
  });
})
/* 监听端口 */
app.listen(3000, () => {
  console.log('listen:3000');
})

Then you can call the interface

index.html

<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Document</title>
</head>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

<body>
	<button id="btn1">发起GET请求</button>
</body>
<script>
	document.querySelector('#btn1').addEventListener('click', function () {
		var url = 'http://localhost:3000/api/list' // 这里设置你本机的ip:端口号
		axios.get(url).then(function (res) {
			console.log(res.data)
		})
	})
</script>

</html>

Guess you like

Origin blog.csdn.net/weixin_44523517/article/details/126678247
Recommended