ajax 请求 koa2 router.post 404

新手上路,请多包涵

我在页面用ajax请求一个路由,返回404, 该方法中使用了request模块调用了一个接口。我想原因可能是路由中request异步数据还没有返回,路由的方法就给返回了,怎么让该路由得到request异步数据再返回给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
        }
    })
})

图片描述

最终控制台把数据打印出来了,但页面却返回404

阅读 3.9k
1 个回答

试试用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
})
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题