您的位置:首页 > Web前端

【Express的demo(一)】 使用express写后端接口、前端调用

2019-07-23 11:32 387 查看

结果展示:

(1)先写后端接口( node + express )

npm init

npm install 

npm install express  --save

app.js文件

[code]const express = require('express')
const app = express()

//设置跨域访问
app.all('*', function(req, res, next) {
   res.header("Access-Control-Allow-Origin", "*");
   res.header("Access-Control-Allow-Headers", "X-Requested-With");
   res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
   res.header("X-Powered-By",' 3.2.1');
   res.header("Content-Type", "application/json;charset=utf-8");
   next();
});

var questions = [
{
name:'张三',
age:12
},
{
name:'柠檬',
age:13
}
]

app.get('/123',function(req,res){
res.status(200);
res.json(questions);
})

app.get('/', (req, res) => res.send('Hello World!'))

app.listen(3000, () => console.log('app listening on port 3000!'))

(2)在使用ajax调取接口

index.html页面

[code]<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="js/jquery-3.4.1.min.js"></script>
<title></title>
</head>
<body>
<button id="btn">点击请求数据</button>

<script>
$(function(){
$('#btn').click(function(){
console.log('按钮被点击')
$.ajax({
type: "GET",
url: "http://localhost:3000/123",
data: '',
dataType: "json",
success: function(data){
console.log(data);
}
});
})
})
</script>
</body>
</html>

-----------------------------------node文件,记得安装依赖

项目地址:demo的git地址

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐