从异步服务返回 axios 响应(Vue + Nuxt)

Den*_*nov 1 javascript vue.js axios nuxt.js

我试图从服务的 axios 响应返回数据,但我总是会从服务接收undefined数据,但在服务内部我有数据。你能告诉我我做错了什么吗?

这是我的服务的样子:

import axios from 'axios';

export default {
  async fetchById (articleId) {
    await axios.post('/api/article', { id: articleId })
      .then(function (response) {
        console.log('axios', response) // valid response
        return response.data
      })
      .catch(function (e) {
        console.error('error', e);
      });
  }
}
Run Code Online (Sandbox Code Playgroud)

还有我在组件中的用法:

async created () {
  const article = await articleService.fetchById('12345')
  console.log('article', article) // there I have undefined
}
Run Code Online (Sandbox Code Playgroud)

fod*_*ma1 5

你缺少一个 return 语句

import axios from 'axios';

export default {
  async fetchById (articleId) {
    // Missing `return` in the next line
    return await axios.post('/api/article', { id: articleId })
      .then(function (response) {
        console.log('axios', response) // valid response
        return response.data
      })
      .catch(function (e) {
        console.error('error', e);
      });
  }
}
Run Code Online (Sandbox Code Playgroud)

我鼓励您开始使用 TypeScript,通过对函数进行适当的类型化,可以轻松避免此类错误。