// 后端服务器有两种
// 1). web服务器: 静态服务器
// 2). api服务器: 暴露接口
// 后端解决跨域问题
// 1). 使用中间件
// 2). 设置请求头
// 2). api服务器: 暴露接口 使用第三方库 express
// 1. 引入第三方库模块
const express = require(‘express’);
// 2. 调用函数的返回值给app对象
const app = express();
// 4. 创建域名
const host = ‘localhost’;
// 5. 创建端口
const port = 1000;
// 6. 创建接口1
app.get(’/user’,(req,res,next) => { // 中间件
// 设置请求头解救跨域(后端)
res.setHeader('Access-Control-Allow-Origin', '*');
res.json({
id: 1,
name: '张三',
age: 25
})
})
// 接口2
app.get(’/demo’,(req,res,next) => { // 中间件
// 设置请求头(后端)
res.setHeader('Access-Control-Allow-Origin', '*');
res.json({
id: 2,
name: '李四',
age: 25
})
})
// 3. 创建api服务器并监听
app.listen(port,host,() => {
console.log(The server is running at: http://${ host }:${ port }
)
})
html