admin管理员组

文章数量:1391947

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('', data, {
    headers: headers
  });
};
postSomething();

Also with curl:

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

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: '', 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, e.g. 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  (ECONNRESET) (.html#errors_mon_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 .git
cd api-demo/
npm install
node src

# In a second terminal download and start Nuxt server
git clone .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!

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./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./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./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, e.g. 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./api (ECONNRESET) (https://nodejs/api/errors.html#errors_mon_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./consuman/api-demo.git
cd api-demo/
npm install
node src

# In a second terminal download and start Nuxt server
git clone https://github./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!

Share Improve this question edited Apr 6, 2020 at 9:36 consuman asked Apr 5, 2020 at 18:23 consumanconsuman 311 silver badge7 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 1

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

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

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

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

this way you can mon your axios code.

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

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./consuman/api-demo.git
cd api-demo/
npm install
node src

# In a second terminal download and start Nuxt server
git clone https://github./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

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.mon["Authorization"] = `Bearer ${token}`;

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

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.

本文标签: javascriptProblem with axios post request from Nuxtjs to external APIStack Overflow