node_代理服务器_request模块

index.js

// request模块

// 代理服务器 => 解决跨域问题
// a.html需要获取B服务器的资源,跨域
// 现在a.html访问本地代理A服务器,用A服务器去访问B服务器
// 然后B服务器返回数据给A服务器,然后返回给a.html

//安装依赖模块 npm i request --save

let [ request, express ] = [ require('request'), require('express') ]
// let request = require('request')
// let express = require('express')
let app = express()
// 基本语法
// 默认请求get请求
// request(url, (err, response, body)=> {
//   // err: 错误信息
//   // response:响应状态
//   // body: 数据体
//   console.log(body) 
// })

let requestParams = `{name:'jack', job: 'web'}`
app.get("/getdata", (req, res) => {
  // post请求
  request({
    // 请求地址
    url: `http://www.baidu.com`,
    //请求方式
    method: 'post',
    // 针对body是不是支持json
    json: true,
    //设置请求头
    headers: {
      "content-type": 'application/json'
    },
    // 请求参数
    body: JSON.stringify(requestParams)
  }, (err, response, body)=>{
    res.end(JSON.stringify(body))
  })
}).listen(8888)

// express框架静态资源托管
app.use(express.static(__dirname + '/src'))

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <script src="https://cdn.bootcss.com/axios/0.19.1/axios.js"></script>
</head>
<body>
  <h1>express首页</h1>
  <button id="getBtn">get请求</button>
</body>
<script type="text/javascript">
  getBtn.onclick = async () => {
    let result = await axios('http://localhost:8888/getdata')
    console.log(result)
  }
</script>
</html>

猜你喜欢

转载自www.cnblogs.com/JunLan/p/12452443.html