鍍金池/ 問答/HTML/ ajax 請求 koa2 router.post 404

ajax 請求 koa2 router.post 404

我在頁面用ajax請求一個路由,返回404, 該方法中使用了request模塊調(diào)用了一個接口。我想原因可能是路由中request異步數(shù)據(jù)還沒有返回,路由的方法就給返回了,怎么讓該路由得到request異步數(shù)據(jù)再返回給ajax。

$("#login").on("click", function () {
        var username = $("#username").val();
        var password = $("#password").val();
        $.post("/users/login", {username:username, password:password}, function (res) {
            alert(res);
        })
    })
router.post('/login', async (ctx, next) => {
    request({
        url: 'http://118.24.41.128:29999/member/login.do',
        method: 'POST',
        json: true,
        headers: {
            'content-type': 'application/json'
        },
        body: ctx.request.body
    }, (err, response, body) => {
        if (!err && response.statusCode === 200) {
            console.log(body)
            ctx.body = body
        }
    })
})

圖片描述

最終控制臺把數(shù)據(jù)打印出來了,但頁面卻返回404

回答
編輯回答
入她眼

試試用request/promise

const rp = require('request-promise')

router.post('/login', async ctx => {
  const result = await rp({
    url: 'http://118.24.41.128:29999/member/login.do',
    method: 'POST',
    json: true,
    headers: {
      'content-type': 'application/json'
    },
    body: ctx.request.body
  })

  ctx.body = result
})
2017年10月25日 02:45