0

I am working in graphql using node js. I want to get the hostname of a server and use it in anywhere of file.

here is my code:

app.use('/api',graphqlHTTP((req,res)=>({

    context:{
      oauth_token:req.oauth_token,
      host : req.headers['host'],
      ip: req.ip
    },
    schema,
    graphiql: true,       
})));

I am accessing it in schema file through resolver. Like:

resolve: (parent, args, context, resolveInfo) => {
        host = context.host;
}

Here I can fetch hostname. But how could I use it in any file?

Upasana
  • 45
  • 9

3 Answers3

0

Although it's not the best practice you can use global object like this:

global.host = host;

And then use global.host wherever you need.

Oficial docs global object

Ilarion Halushka
  • 2,083
  • 18
  • 13
0

You can use global object which is keyword in Node.

global.hostname = req.headers['host']

and use it anywhere in app.

Cihan
  • 108
  • 7
0

If the hostname is a static value and is something you have control of I would suggest to use the node environmental variables. There are 2 common ways to use it: 1. command line 2. .env file

1) Simply indicate the name of the variable following by equal sign and then the value itself. After that start your node server

HOST=localhost node server.js

And then you can use it in your app like so:

// server.js
const host = process.env.HOST;

2) Create a .env file in the root of your app and set the variables there:

HOST=localhost
PORT=8080
API_KEY=123123

I would personally prefer the second one as you just set it up once and no need to type it in the console every time you start the server. Just don't forget to include it in your .gitignore as your history will have references to your secrets then

Mark Shulhin
  • 119
  • 5
  • Could you please provide me some more details for 2nd approach? Or could you provide me some link after that i can understand clearly? – Upasana Apr 26 '19 at 09:10
  • Yes, there is plenty of helpful articles on medium, perhaps this one will provide you more context https://medium.com/the-node-js-collection/making-your-node-js-work-everywhere-with-environment-variables-2da8cdf6e786 – Mark Shulhin Apr 26 '19 at 13:11
  • I have created a .env file. Could you please explain how can i give credential for the different server? – Upasana Apr 30 '19 at 05:51
  • Sorry, I'm not entirely sure what do you mean by 'give for the different server', could you please elaborate on that? – Mark Shulhin Apr 30 '19 at 11:56
  • This is the link - https://stackoverflow.com/questions/55904884/how-to-connect-database-with-different-credential-dynamically-for-different-serv/55905212?noredirect=1#comment98483614_55905212 – Upasana May 02 '19 at 05:11