I'm developing a Vue.js application which has only frontend (no server) and send a lot of requests to different APIs. The originally quite simple app became more complex. And there are problems with some APIs, because browsers do not accept the responses due to CORS. That is why I'm trying to test, if I can migrate the app to Nuxt.js.
My approach is as follows (inspired by this comment), but I expect, that there is probably a better way to send the requests from the client over the server.
pages/test-page.vue
methods: {
  async sendRequest(testData) {
    const response = await axios.post('api', testData)
    // Here can I use the response on the page.
  }
}
nuxt.config.js
serverMiddleware: [
  { path: '/api', handler: '~/server-middleware/postRequestHandler.js' }
],
server-middleware/postRequestHandler.js
import axios from 'axios'
const configs = require('../store/config.js')
module.exports = function(req, res, next) {
  let body = ''
  req.on('data', (data) => {
    body += data
  })
  req.on('end', async () => {
    if (req.hasOwnProperty('originalUrl') && req.originalUrl === '/api') {
      const parsedBody = JSON.parse(body)
      // Send the request from the server.
      const response = await axios.post(
        configs.state().testUrl,
        body
      )
      req.body = response
    }
    next()
  })
}
middleware/test.js (see: API: The Context)
export default function(context) {
  // Universal keys
  const { store } = context
  // Server-side
  if (process.server) {
    const { req } = context
    store.body = req.body
  }
}
pages/api.vue
<template>
  {{ body }}
</template>
<script>
export default {
  middleware: 'test',
  computed: {
    body() {
      return this.$store.body
    }
  }
}
</script>
When the user makes an action on the page "test", which will initiate the method "sendRequest()", then the request "axios.post('api', testData)" will result in a response, which contains the HTML code of the page "api". I can then extract the JSON "body" from the HTML.
I find the final step as suboptimal, but I have no idea, how can I send just the JSON and not the whole page. But I suppose, that there must be a much better way to get the data to the client.
There are two possible solutions:
Ad 1. Proxy
The configuration of the proxy can look like this:
nuxt.config.js
module.exports = {
...
  modules: [
    '@nuxtjs/axios',
    '@nuxtjs/proxy'
  ],
  proxy: {
    '/proxy/packagist-search/': {
      target: 'https://packagist.org',
      pathRewrite: {
        '^/proxy/packagist-search/': '/search.json?q='
      },
      changeOrigin: true
    }
  },
  ...
}
The request over proxy can look like this:
axios
  .get('/proxy/packagist-search/' + this.search.phpLibrary.searchPhrase)
  .then((response) => {
    console.log(
      'Could get the values packagist.org',
      response.data
    )
    }
  })
  .catch((e) => {
    console.log(
      'Could not get the values from packagist.org',
      e
    )
  })
Ad 2. API
Select Express as the project’s server-side framework, when creating the new Nuxt.js app.
server/index.js
...
app.post('/api/confluence', confluence.send)
app.use(nuxt.render)
...
server/confluence.js (simplified)
const axios = require('axios')
const config = require('../nuxt.config.js')
exports.send = function(req, res) {
  let body = ''
  let page = {}
  req.on('data', (data) => {
    body += data
  })
  req.on('end', async () => {
    const parsedBody = JSON.parse(body)
    try {
      page = await axios.get(
        config.api.confluence.url.api + ...,
        config.api.confluence.auth
      )
    } catch (e) {
      console.log('ERROR: ', e)
    }
  }
  res.json({
    page
  })
}
The request over API can look like this:
this.$axios
  .post('api/confluence', postData)
  .then((response) => {
    console.log('Wiki response: ', response.data)
  })
  .catch((e) => {
    console.log('Could not update the wiki page. ', e)
  })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With