Calling another webservice from my Strapi service

System Information
  • Strapi Version: v4.4.4
  • Operating System: Digital Ocean
  • Database:
  • Node Version:
  • NPM Version:
  • Yarn Version:

Hey Everyone, hope this is not a dumb question, as i am fairly new to the Strapi-World…

What i’d like to do is create a Strapi-Service that returns some data depending on the response of another service hosted elsewhere on the internet. Something along the lines of (pseudocode):

var response = otherservice.doesEntryExist( entryNr )
if( response.false ) {
return strapi.makeNewEntryNumber()
} else return -1

I managed to create a custom plugin on my local strapi instance (will be pushed to production on DigitalOcean) that returns ‘hello world’ style placeholder stuff. Now i’m stuck on how to make the call to my other service. it seems i either cannot execute http stuff from inside my-service.js at all, or am just having trouble figuring out how to make node.js wait for the response to come in (making it async? await?)

this is what i have so far

'use strict';

module.exports = ({ strapi }) => ({
    async validateWorldRequested() {
	  
	const axios = require('axios');

	await axios.get('http://www.example.com/')
	.then(response => {
		//return response.data.url;
		//return response.data.explanation;
		return 'responsense'
	})
	.catch(error => {
		return 'error in validateWorldRequested'
	});
  },
});

most promising return i can manage to get out of it is “[object Promise]”

What am i missing? Am i holding it wrong?
Can this even be done in the way i am trying to do it? What fundamental principle am i ignoring/breaking?

Some pointers would be greatly appreciated!
THX in advance,
Ph

Not sure what is wrong with your code, but try this:

'use strict';
const axios = require('axios');

module.exports = ({ strapi }) => ({
  async validateWorldRequested() {
	try {
        const response = await axios.get('http://www.example.com/')
        console.log(response)    
        } 
        catch(error) {
            // handle error
        }
  },
});
1 Like

Not shure what was wrong with my code, either, but your snippet worked! Thank you so much, @Izuorah_Dubem