fetch graphql data from nodejs to nextjs (SSR) - node.js

I have nextjs Project, where I use SSR for fetch data from nodejs(graphql) but it works only localhost(dev/production), When I upload the project on vercel I get "500: Internal Server Error", I will share my code and required details below:
I use "graphql-request" on Nextjs
import { gql, request } from "graphql-request";
export async function getServerSideProps(context) {
const endPoint = "http://localhost:4000/";
const query = gql`
query {
exactlyUser(id: "63c3cf0aea56b467893c92d3") {
username
}
}
`;
const data = await request(endPoint, query);
return {
props: {
data: data,
},
};
}
I also give you vercel Error:
[HEAD] /_next/data/U_aH1k5dl2EQA1IzXATL6/index.json
2023-01-17T16:52:11.277Z ddd8e632-1ffa-4772-94c0-aa01e2348bb7 ERROR FetchError: request to http://localhost:4000/ failed, reason: connect ECONNREFUSED 127.0.0.1:4000
at ClientRequest.<anonymous> (/var/task/node_modules/node-fetch/lib/index.js:1491:11)
at ClientRequest.emit (node:events:513:28)
at Socket.socketErrorListener (node:_http_client:494:9)
at Socket.emit (node:events:513:28)
at emitErrorNT (node:internal/streams/destroy:151:8)
at emitErrorCloseNT (node:internal/streams/destroy:116:3)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
type: 'system',
errno: 'ECONNREFUSED',
code: 'ECONNREFUSED',
page: '/'
}
RequestId: ddd8e632-1ffa-4772-94c0-aa01e2348bb7 Error: Runtime exited with error: exit status 1
Runtime.ExitError

Seems like when you deploy the Next.js app to Vercel, the API is not accessible. This is the cause of the "500: Internal Server Error" you're seeing.
Try to change the API endpoint URL to the publicly accessible URL of your GraphQL API, instead of using "http://localhost:4000/". This should allow the Next.js app to fetch data from the API when it's running on Vercel.
Avoid hardcoding the API endpoint.

Related

How to Use Node SMPP to Connect to InetLab SMPP Server

I am trying to build an SMS an SMS Client using NodeJS which should connect to ``Inetlab ```` SMPP Server to send Short messages. I downloaded Inetlab SMPP client and Server and run them both. When I try to connect and send an SMS from the client via port 7777 (Not that it matters), The connection is bound successfully and the message is sent across.
My problem is when I try connect to the same local SMPP server via a client that I have bult with NodeJS using the node-smpp library, the connection fails even though I am using the same localhost and port 7777.
Below is my connection code:
module.exports = class{
constructor(){
this.session = null
this.smppConfig = {
url:"smpp://localhost:7777",
auto_enquire_link_period:10000,
debug:true
}
}
StartSmppSession= ()=>{
return new Promise( async(resolve, reject)=>{
try{
console.log(this.smppConfig)
this.session = smpp.connect(this.smppConfig,()=>{
this.session.bind_transceiver({
system_id:process.env.SMPP_SYSTEM_ID,
password:process.env.SMPP_PASSWORD
},(pdu)=>{
if(pdu.command_status === 0){
resolve({message:"Connection bound successfully!"})
}else{
reject({message:"Failed to bind!",pdu})
}
})
})
}catch(err){
//reject(err.message)
}
})
}
sendSMS = (payload)=>{
return new Promise(async (resolve, reject)=>{
try{
//payload = {destination_addr:"phone_number", "short_message":"The message here"}
this.session.submit_sm(payload, async (pdu)=>{
pdu.command_status === 0 ? resolve("Message successfully sent!") : reject("Failed to send SMS!")
})
}catch(err){
reject(err.message)
}
})
}
}
When I invoke the StartSmppSession() function in my controller, I get the following error log:
2022-12-06T09:30:40.973Z - cli - 315644 - socket.error - connect ECONNREFUSED ::1:7777 - {"errno":-4078,"code":"ECONNREFUSED","syscall":"connect","address":"::1","port":7777}
node:events:491
throw er; // Unhandled 'error' event
^
Error: connect ECONNREFUSED ::1:7777
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1284:16)
Emitted 'error' event on Session instance at:
at Socket.<anonymous> (C:\Users\c.mwale\Desktop\NRB API Test\Notifications Module\SMSGateway\src\SMS_Outgoing\node_modules\smpp\lib\smpp.js:119:8)
at Socket.emit (node:events:513:28)
at emitErrorNT (node:internal/streams/destroy:151:8)
at emitErrorCloseNT (node:internal/streams/destroy:116:3)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
errno: -4078,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '::1',
port: 7777
}
I understand that there is a SMPP library for .NET documented on the inetlab website, but I am of the view this the intent of using a C# example was not to dictate the framework nor language of implementation.

MongoDB Atlas - How to fix 'TransientTransactionError' on shared web-hosting

TransientTransactionError when attempting to connect from shared web-host to Mongo Atlas
I actually had this working at one point but I had to wipe and restart my project from scratch on my web host. Now seemingly out of nowhere I keep getting the above-mentioned error when trying to connect to Atlas. I have already tried whitelisting IP addresses including both my server IP as well as 0.0.0.0/0 (the 'allow all' wildcard) in Atlas.
I have also tried using the 'full driver' snippet instead of mongoose but still receive the same error. Lastly, I want to point out that the exact same code works just fine on my local machine.
Here's my function:
const mongoose = require("mongoose");
const config = require("./config");
module.exports = cb => {
if (mongoose.connection.readyState < 1) {
mongoose.connect(config.db).then(
() => {
console.log("Database linking successful!");
return cb ? cb : null;
},
err => {
console.log("Failed to connect to database.", err);
}
);
}
};
Here's what the error message looks like:
{ MongoNetworkError: failed to connect to server [<mongodb-shard-goes-here>.mongodb.net:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 54.145.177.180:27017]
at Pool.<anonymous> (/home/titanesp/public_html/server/node_modules/mongodb-core/lib/topologies/server.js:431:11)
at Pool.emit (events.js:182:13)
at connect (/home/titanesp/public_html/server/node_modules/mongodb-core/lib/connection/pool.js:557:14)
at makeConnection (/home/titanesp/public_html/server/node_modules/mongodb-core/lib/connection/connect.js:39:11)
at callback (/home/titanesp/public_html/server/node_modules/mongodb-core/lib/connection/connect.js:261:5)
at TLSSocket.err (/home/titanesp/public_html/server/node_modules/mongodb-core/lib/connection/connect.js:286:7)
at Object.onceWrapper (events.js:273:13)
at TLSSocket.emit (events.js:182:13)
at emitErrorNT (internal/streams/destroy.js:82:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:50:3)
at process._tickCallback (internal/process/next_tick.js:63:19)
name: 'MongoNetworkError',
errorLabels: [ 'TransientTransactionError' ],
[Symbol(mongoErrorContextSymbol)]: {} }

How to fire POST request using inline editor in dialogflow?

Code:
var rp = require('request-promise');
var options = {
method: 'POST',
uri: 'http://c663fe13.ngrok.io/ap/lighton',
body: {"color": 'white'},
json: true // Automatically stringifies the body to JSON
};
rp(options)
.then(function (parsedBody) {
// POST succeeded...+
console.log("parsedBody", parsedBody);
})
.catch(function (err) {
// POST failed...
console.log("err", err);
});
but this gives me the following error:
{ RequestError: Error: getaddrinfo EAI_AGAIN c663fe13.ngrok.io:80
at new RequestError (/srv/node_modules/request-promise-core/lib/errors.js:14:15)
at Request.plumbing.callback (/srv/node_modules/request-promise-core/lib/plumbing.js:87:29)
at Request.RP$callback [as _callback] (/srv/node_modules/request-promise-core/lib/plumbing.js:46:31)
. . .
name: 'RequestError', message: 'Error: getaddrinfo EAI_AGAIN
c663fe13.ngrok.io:80',
cause: { Error: getaddrinfo EAI_AGAIN
c663fe13.ngrok.io:80
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:67:26)
errno: 'EAI_AGAIN',
code: 'EAI_AGAIN',
syscall: 'getaddrinfo',
hostname: 'c663fe13.ngrok.io',
host: 'c663fe13.ngrok.io',
port: 80 },
I trie to call that API with postman and it's working fine.
If you are using a free account you will not be able to hit any 3rd party services from Firebase cloud functions. It would be better if you write down your own webhook code and using fulfillment integrate that webhook with your Dialogflow agent if you are going to use the free account.
UPDATE
Check out the code snippets I have shared here. You can use that to integrate ExpressJS and then add your POST code and host it locally. Expose the local server using ngrok and then put that URL in fulfillment.

Problem with Facebook Graph API in Node.js application

I've created the node.js application which is connected with Facebook Graph API. The problem is that when I am using request to get the data from the URL, sometimes I am not receiving the data but this error message:
{
Error: connect ETIMEDOUT 31.13.81.9:443
at Object._errnoException (util.js:992:11)
at _exceptionWithHostPort (util.js:1014:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1186:14)
code: 'ETIMEDOUT',
errno: 'ETIMEDOUT',
syscall: 'connect',
address: '31.13.81.9',
port: 443
}
When I paste the URL to the browser I am receiving the data from API without any problem.
The request which gets the Facebook API data
request({url:`https://graph.facebook.com/v3.2/me?fields=posts%7Bcomments%7Blike_count%7D%2Cshares%2Ccreated_time%2Csource%2Clikes.summary(true)%7D%2Cfan_count&period=day&since=${selectedDateFrom}&until=${selectedDateTo}&access_token=${accessToken}`,
json: true
}, (err, response, body) => {
if (err) {
console.log(err)
} else {console.log(body);}
I wonder why the problem is happening in my application, and why in the browser everything is fine?

Connect ETIMEDOUT on Azure App Service when calling HTTP endpoint without specify maxSockets

I have some timeout problems when calling multiple times an HTTP[S] endpoint from node.js inside an Azure App Service.
Here my code to demostrate the problem.
const fetch = require('node-fetch');
const https = require("https");
const agent = new https.Agent();
function doWork() {
const works = [];
for (let i = 0; i < 50; i++) {
const wk = fetch('https://www.microsoft.com/robots.txt', { agent })
.then(res => res.text())
.then(body => console.log("OK", i))
.catch((err) => console.log("ERROR", i, err));
works.push(wk);
}
return Promise.all(works);
}
doWork()
.catch((err) => {
console.log(err);
});
When running this app 3 or 4 times inside a Standard Medium App Service (I'm running it using Kudu but I discover this error inside a standard web app) I get the following error for every requests:
{ FetchError: request to https://www.microsoft.com/robots.txt failed, reason: connect ETIMEDOUT 23.206.106.109:443
at ClientRequest.<anonymous> (D:\home\site\test\test-forge-calls\node_modules\node-fetch\lib\index.js:1393:11)
at emitOne (events.js:96:13)
at ClientRequest.emit (events.js:188:7)
at TLSSocket.socketErrorListener (_http_client.js:310:9)
at emitOne (events.js:96:13)
at TLSSocket.emit (events.js:188:7)
at emitErrorNT (net.js:1276:8)
at _combinedTickCallback (internal/process/next_tick.js:74:11)
at process._tickCallback (internal/process/next_tick.js:98:9)
message: 'request to https://www.microsoft.com/robots.txt failed, reason: connect ETIMEDOUT 23.206.106.109:443',
type: 'system',
errno: 'ETIMEDOUT',
code: 'ETIMEDOUT' }
After some minutes (5/6) without performing requests the above code works again.
I have tried with both node-fetch (https://www.npmjs.com/package/node-fetch) and request (https://www.npmjs.com/package/request). Same results.
The same problem occurs if I not specify an agent and is not related to the destination endpoint, I have tried with many different endpoints (private or public).
According to Microsoft Best Practices node.js applications should use a keep alive agent with the following configuration:
var keepaliveAgent = new Agent({
maxSockets: 40,
maxFreeSockets: 10,
timeout: 60000,
keepAliveTimeout: 300000
});
In fact when creating the agent with:
const agent = new https.Agent({ maxSockets: 100 });
everything works as expected.
Is this behavior expected? What is the best practice for node.js? It is fine to always specify an agent with maxSockets also outside Azure?
UPDATE:
The other strange behavior is that if I run the above code using node index 3 or 4 times I expect that connections are closed when node process exit, but seems that the connections remain open for some minutes. This can be the effect of the TIME_WAIT state?

Resources