首页 > 解决方案 > 从 Nuxt.js 到外部 API 的 axios 发布请求出现问题

问题描述

我现在尝试了好几个小时,从 Nuxt 向我的外部 api 发送一个简单的发布请求。

它可以从单独的节点实例按预期工作,我可以根据需要使用以下内容进行 POST 和 GET:

const headers = {
  'Content-Type': 'application/json',
  'access-token': 'myTokenXYZ123'
};
const data = { test: 'Hello!' };

const postSomething = () => {
  axios.post('https://myapidomain.com/api', data, {
    headers: headers
  });
};
postSomething();

还有curl

curl -X POST -H 'access-token: myTokenXYZ123' -H 'Content-Type: application/json' -d '{ "test": "Hello!" }' https://myapidomain.com/api

到目前为止一切顺利,现在我想在我的 Nuxt 项目中实现它。我必须先设置一个 http 代理,我这样做是nuxt.config.js这样的:

[...]

modules: [
    '@nuxtjs/axios',
    '@nuxtjs/proxy'
  ],
  proxy: {
    '/my-api/': { target: 'https://myapidomain.com/api', pathRewrite: {'^/my-api/': ''} },
  },
  axios: {
    proxy: true
  },

[...]

我非常有信心代理正在工作,因为我可以使用以下方法获取数据:

methods: {
  async getSomething() {
    let requested = await this.$axios.get('/my-api/', {
       headers: this.headers
    });
    return requested.data;
  }
}

但无论我做什么,POST 请求都不起作用。这就是我尝试的方式:

methods: {
  postSomething() {
    const data = { test: 'Hello!' };

    this.$axios.post('/my-api/', data, {
      headers: {
        'Content-Type': 'application/json',
        'access-token': 'myTokenXYZ123'
      }
    });
  }
}

我尝试了各种不同的格式,例如:

methods: {
  postSomething() {
    const headers = {
      'Content-Type': 'application/json',
      'access-token': 'myTokenXYZ123'
    };
    const data = { test: 'Hello!' };
    const options = {
      method: 'post',
      url: '/my-api/',
      data: data,
      transformRequest: [(data, headers) => {
        return data;
      }]
    };
    this.$axios(options);
  }
}

但这似乎不起作用。请求正在运行并在一段时间后中止,终端中出现以下错误:

ERROR  [HPM] Error occurred while trying to proxy request  from localhost:3000 to https://myapidomain.com/api (ECONNRESET) (https://nodejs.org/api/errors.html#errors_common_system_errors)

我已经尝试过的其他一些事情:

重现步骤:

# Download and start API server
git clone https://github.com/consuman/api-demo.git
cd api-demo/
npm install
node src

# In a second terminal download and start Nuxt server
git clone https://github.com/consuman/api-demo-nuxt.git
cd api-demo-nuxt
npm install
npm run dev

# Navigate to http://localhost:3000
# Relevant code is in /api-demo-nuxt/pages/index.vue

要测试 API 是否正常工作,您可以使用 curl 进行 POST:

curl -X POST -H 'access-token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjaGVjayI6dHJ1ZSwiaWF0IjoxNTg2MTYzMjAxLCJleHAiOjE2MTc2OTkyMDF9.vot4mfiR0j6OewlJ0RWgRksDGp-BSD4RPSymZpXTjAs' -H 'Content-Type: application/json' -d '{ "testData": "Hello from API, posted from curl, please overwrite me!" }' http://localhost:3001/api

感谢您的阅读。任何提示将不胜感激!

标签: javascriptnode.jsaxioshttp-postnuxt.js

解决方案


希望你使用@nuxtjs/axios模块,如果是的话,你可以使用拦截器

https://axios.nuxtjs.org/helpers.html#interceptors

export default function ({ $axios, redirect }) {
  $axios.onRequest(config => {
    config.headers.common['Authorization'] = `Bearer token`;
  })

  $axios.onError(error => {
    if(error.response.status === 500) {
      redirect('/sorry')
    }
  })
}

这样您就可以共享您的 axios 代码。

关于您的帖子请求,您能否分享更多详细信息或任何工作示例!!!


推荐阅读