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>
复制代码

 

posted @   前端之旅  阅读(434)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示