0

node.js axios 回调问题

 2 years ago
source link: https://www.v2ex.com/t/802686
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

V2EX  ›  Node.js

node.js axios 回调问题

  AnjingJingan · 4 小时 26 分钟前 · 516 次点击

浏览器发起请求,后端 node.js 收到浏览器请求后用 axios 请求一个接口,如何把接口的返回结果给浏览器?

const http = require('http')
const axios = require('axios')
const qs = require('qs')
var request = require('request');

//    返回一个 Server 实例
const server = http.createServer()

async function getData (){
    let obj = {
        'type': "1"
    }

    url = "http://httpbin.org/post"
    const promise = axios.post(url, qs.stringify(obj), {
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
        }
    })

    const dataPromise = promise.then((response)=>response.data)
    return dataPromise
}


server.on('request', function (request, response) {

    console.log('收到客户端的请求了,请求路径是:' + request.url)

    response.write('hello')
    getData().then((res) => {
        // response.write(res)
        console.log(res)  //res 怎么返回给前端
    })
    // 告诉客户端,我的话说完了,你可以呈递给用户了
    response.end()
})

server.listen(3000, function () {
    console.log('服务器启动成功了,http://127.0.0.1:3000/')
})

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK