【Web前端问题】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
回答:
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
})
以上是 【Web前端问题】ajax 请求 koa2 router.post 404 的全部内容, 来源链接: utcz.com/a/136421.html
