简体   繁体   中英

Problem with axios post request from Nuxt.js to external API

I'm trying for many hours now, to get a simple post request to my external api working from Nuxt.

It works as expected from a seperate node instance , I can POST and GET as needed with the following:

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();

Also with curl :

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

So far so good, now I want to implement this in my Nuxt project. I had to set up a http proxy first, which I did in nuxt.config.js like this:

[...]

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

[...]

I'm pretty confident that the proxy is working, because I can get the data with the following method:

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

But whatever I do, the POST request does not work. This is how I tried:

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

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

I tried various different formats, eg like this:

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);
  }
}

But it does not seem to work. The request is running and aborts after a while with the following error in the terminal:

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)

A few other things I already tried:

  • Running API and Nuxt locally

  • Using axios imported in template and as nuxt module

  • Request from builded and productive version

  • Async and synchronous methods

Steps to reproduce:

# 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

To test, if the API is working, you can POST with curl:

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

Thank you for reading. Any hint would be much appreciated!

Hope You are Using @nuxtjs/axios module if yes than you can use interceptors

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')
    }
  })
}

this way you can common your axios code.

And regarding your post request can you please share more details or any working example!!!

If you're having trouble using axios within nuxt. Make sure you have access to axios itself, either through imports or context.

import axios from "@nuxtjs/axios";
const res = await axios.post('/api/v1/auth', {email, password });

or context

// For methods and vuex, you have access to 'this'
const res = await this.$axios.$post('/api/v1/auth', {email, password });

// For nuxt middleware, you have access to 'context'
const res = await context.$axios.$get('/api/v1/user');

Including headers

this.$axios.defaults.headers.common["Authorization"] = `Bearer ${token}`;

And lastly, make sure you're console logging the server endpoints (middleware and routes) to ensure you're hitting everything properly.

I have found the problem. There was a server middleware configured, that was not needed anymore. It triggered at every POST request.

Stupid mistake, but this is how you learn, right? xD

The steps to reproduce are a working demo now, in case anyone needs something similar.

Cheers!

Here is the working demo again:

# 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

In my case, I was putting the trigger button inside the form. This was triggering the function (where I call axios) call and also the XHR call that usually takes place when you send a From.

In order to fix it and only trigger the axios call, just take the button off the Form tag.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM