初始化,创建package.json文件:
npm init
安装 express 框架:
npm install express --save
新建server.js
const express = require('express')
const app = express()
const port = 5000
//设置跨域访问
app.all("*", function(req, res, next) {
//设置允许跨域的域名,*代表允许任意域名跨域
res.header("Access-Control-Allow-Origin", req.headers.origin || '*');
// //只允许http://xxx.xx.xx/可跨
//res.header('Access-Control-Allow-Origin', 'http://xxx.xx.xx/');
//允许的header类型
res.header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With");
//跨域允许的请求方式
res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
// 可以带cookies
res.header("Access-Control-Allow-Credentials", true);
if (req.method == 'OPTIONS') {
res.sendStatus(200);
} else {
next();
}
})
var data = [{
label: '早晨',
value: '面条'
},
{
label: '中午',
value: '煎饼'
}
];
//写个接口list
app.get('/list', function(req, res) {
res.status(200),
res.json(data)
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
运行服务器
node server.js
新建index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$.ajax({
type: 'get',
url: 'http://localhost:5000/list',
success: function(data) {
console.log(data);
},
error: function() {
console.log('error');
}
})
</script>
</body>
</html>