Home > Enterprise >  How to make external GET request using Nuxt.js Server Middleware
How to make external GET request using Nuxt.js Server Middleware

Time:08-22

I am working with a Nuxt.js v2.15.8 project and I am attempting to use the server middleware feature that Nuxt offers for A custom API endpoint. https://nuxtjs.org/docs/configuration-glossary/configuration-servermiddleware/#custom-api-endpoint

What I am trying to accomplish:

Use Nuxt server middleware to make a GET request to a 3rd party api to retrieve data. When I try to set this up and make the request to the endpoint in Postman, I get an error

<!doctype html>
<html data-n-head-ssr lang="en" data-n-head="{"lang":{"ssr":"en"}}">

<head>
    <title>This page could not be found</title> etc....

How do I use the Nuxt server middleware to make api calls to external api's?

Nuxt.config.js

  serverMiddleware: [
    {
      path: '/api/server-middleware',
      handler: '~/api/getData.js',
    },
  ],

~/api/getData.js

const bodyParser = require('body-parser');
const app = require('express')();

app.use(bodyParser.json());

app.all('https://jsonplaceholder.typicode.com/todos/1', (req, res) => {
  res.json({ data: res.data });
});

module.exports = app;

In Postman I try to make a GET request to http://localhost:3000/api/server-middleware after running npm run dev and my Nuxt project is running.

Am I misunderstanding how this is supposed to work? Is the Server Middleware for internal api calls only?

CodePudding user response:

Applying the least possible amount of changes to your shared code gives us the following

getData.js

import axios from 'axios'
const app = require('express')()

app.all('/jsonplaceholder/:id', async (req, res) => {
  const { data } = await axios(
    `https://jsonplaceholder.typicode.com/todos/${req.params.id}`
  )
  res.json({ ...data })
})

module.exports = app

/pages/index.vue

<template>
  <div>
    <input id="name" v-model="todoId" type="text" name="name" />
    <button @click="callNuxtApi">try local Nuxt API</button>
    <div>
      Response from the backend:
      <pre>{{ response }}</pre>
    </div>
  </div>
</template>

<script>
export default {
  name: 'JsonPlaceholderPage',
  data() {
    return {
      todoId: 1,
      response: {},
    }
  },
  methods: {
    async callNuxtApi() {
      const response = await this.$axios.$get(`/api/server-middleware/jsonplaceholder/${this.todoId}`)
      console.log('response', response)
      this.response = response
    },
  },
}
</script>

As you can see, /jsonplaceholder/:id is something more reasonable considering that it will be prefixed by /api/server-middleware/ already.
Having https:// inside of a path is not really nice to the browser overall.

PS: you need to install axios and express for it to work. @nuxtjs/axios will not work here.


This answer joins my other one here: https://stackoverflow.com/a/72102209/8816585

  • Related