2
votes

I'm currently converting a vue application to use the NUXT framework. To add support for SSR to my application and have come across the following issue when trying to use asyncData with multiple data sources on a single page.

I'm trying to setup asyncData to get data from 2 separate data sources that are required for the page to work. Now the code works on the client-side when the Promise.all resolves it gets both sets of data. However, on the server-side the promises when console.log the promises are both pending and causes Nginx to timeout and give a 504 bad gateway error.

I have tried to get this to work use async/await and promise.all with no avail. see code samples for both below.

Import functions getData and getJsonFile are both using Axios and returning resolved promises with objects of data.

// Using async/await
export default {
  async asyncData(context) {
    const nameData = await getData('getInformationByNames', {
      names: [context.params.name],
      referingPage: `https://local.test.com${context.route.fullPath}`
    });

    const content = await getJsonFile(
      `/data/pages/user/${context.params.id}`
    );

    return {
      names: nameData,
      content
    };
  }
}
// Using Promise.all
export default {
  async asyncData(context) {
    const [nameData, content] = await Promise.all([
      getData('getInformationByNames', {
        names: [context.params.name],
        referingPage: `https://local.test.com${context.route.fullPath}`
      }),
      getJsonFile(`/data/pages/user/${context.params.id}`)
    ]);
    return {
      names: nameData,
      content
    };
  }
}
// getJsonFile

import axios from 'axios';
import replaceStringTokens from '@/scripts/helpers/replaceStringTokens';

export default function getJsonFile(path, redirect = true) {
  const jsonFilePath = `${path}.json`;

  return axios.get(jsonFilePath).then((response) => {
    if (typeof response.data === 'object') {
      return replaceStringTokens(response.data);
    }
    return false;
  });
}
// getData

import axios from 'axios';
import getUserDevice from '@/scripts/helpers/getUserDevice';

// require php-serialize node package to serialize the data like PHP would for the api endpoint.
const Serialize = require('php-serialize');

export default function getData(action, data) {
  const dataApiAddress = '/api/getData.php';

  const dataToPass = data || {};
  // all actions available on the api will need to know the users device so add it to the data.
  dataToPass.userDevice = getUserDevice();

  // package the data like the api expects to receive it
  const serializedAndEncodedData = encodeURIComponent(
    Serialize.serialize(dataToPass)
  );

  const axiosParams = {
    action,
    data: serializedAndEncodedData
  };

  return axios
    .get(dataApiAddress, {
      params: axiosParams
    })
    .then((response) => {
      return response.data.data;
    })
    .catch((error) => {
      console.log(error);
      return false;
    });
}

I would expect that the promises resolve and both sets of data are returned an available for the page to use on both the client and server-side.

Is there a better way to get multiple sets of data or a way to debug the server-side so that I can see what is causing the promises to not resolve on the server?

1
please post the getData() function and the getJsonFile() functionSimon Dehaut
Updated the post to include the two functionsBen Humphries
did you set axios baseurl? You are likely quering localhost on serverAldarund
I just wrote somethink like your async/await function for testing (// Using async/await ...) and I get : jsfiddle.net/zvtde613/1 If you have a 504 error and If we don't see server-side sode it's will very difficult to see what's wrong. What's in your /api/getData.php ?Simon Dehaut
Unfortunately due to legal reasons, I am unable to share the server-side code. Thank you for taking the time to look I will try and adapt your jsfiddle you shared to get it to work without the functions and then once working abstract the code back to a function. Aldarund thats for the suggestion I will set up a base URL for Axios in my nuxt config and see if that will fix my issueBen Humphries

1 Answers

0
votes

Fixed the issue the problem was with some discrepancies in the data being queried on the API. The data in the database was using an uppercase letter at the start that must have been input incorrectly. So this was causing the promise to not resolve due to the API sending a query for the lowercase version and in turn causing Nginx to timeout.