i am getting error like this how to resolve? - mongodb

xhr.js:247 POST http://localhost:5000/questions net::ERR_CONNECTION_REFUSED
AxiosError {message: 'Network Error', name: 'AxiosError', code: 'ERR_NETWORK', config: {…}, request: XMLHttpRequest, …}
code:"ERR_NETWORK"
config
:
{transitional: {…}, adapter: Array(2), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …}
message
:
"Network Error"
name
:
"AxiosError"
request
:
XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}
stack
:
"AxiosError: Network Error\n at XMLHttpRequest.handleError (http://localhost:3000/static/js/bundle.js:54654:14)"
[[Prototype]]
:
Error

Related

Next.js + Apollo + Mongodb : Unable to have acces to Apollo context in SSR mode

i am triying to connect MongoDB with the NextJS API route Apollo example:
https://github.com/vercel/next.js/blob/canary/examples/api-routes-apollo-server-and-client
I cannot find any official doc. So i follow this topic:
Connect Apollo with mongodb
The idea is to connect Mongodb from the context of ApolloServer
pages/api/graphql.js
import { ApolloServer } from 'apollo-server-micro';
import { schema } from '../../apollo/schema';
import { connectToDatabase } from '../../utils/mongodb';
const apolloServer = new ApolloServer({
schema,
context: async () => {
const { db } = await connectToDatabase();
return { db };
},
});
export const config = {
api: {
bodyParser: false,
},
};
export default apolloServer.createHandler({ path: '/api/graphql' });
the "connectToDatabase" is coming from the example "with-mongo"
https://github.com/vercel/next.js/blob/canary/examples/with-mongodb/util/mongodb.js
There is 3 ways of rendering pages in NextJS. When i connect my db like so (inside the ApolloServer context) it works just fine with the client side rendering but not at all with the Static and Server Side Rendering. The context inside my resolver function is undefined.
apollo/resolvers.js
export const resolvers = {
Query: {
async getAllCards(_parent, _args, _context, _info) {
console.log('_context resolver :>> ', _context);
const res = await _context.db.db
.collection('cards')
.find({})
.limit(20)
.toArray();
console.log('res :>> ', res);
return res;
},
},
};
At that point i tried to follow this topic
Next.js graphql context is empty {} on SSR getServerSideProps
Following thoses steps i am ending with 2 files modified:
pages/api/graphql
import { ApolloServer } from 'apollo-server-micro';
import { schema } from '../../apollo/schema';
import { connectToDatabase } from '../../utils/mongodb';
async function contextResolver(ctx) {
ctx.db = await connectToDatabase();
return ctx;
}
const apolloServer = new ApolloServer({
schema,
context: contextResolver,
});
export const config = {
api: {
bodyParser: false,
},
};
export default apolloServer.createHandler({ path: '/api/graphql' });
and
pages/explore_SSR.js
import gql from 'graphql-tag';
import Link from 'next/link';
import { initializeApollo } from '../apollo/client';
import { connectToDatabase } from '../utils/mongodb';
const Explore = () => {
return (
// UI Stuff
)
}
export async function getServerSideProps(ctx) {
console.log('ctx :>> ', ctx);
async function contextResolver(ctx) {
ctx.db = await connectToDatabase();
return ctx;
}
await contextResolver(ctx);
console.log('ctx after :>> ', ctx);
const apolloClient = initializeApollo(null, ctx);
await apolloClient.query({
query: gql`
query GetAllMementoQuery {
getAllMemento {
title
}
}
`,
});
return {
props: {
props: { initialApolloState: apolloClient.cache.extract() },
},
};
}
export default Explore;
result of the console.log: console.log('ctx after :>> ', ctx);
ctx after :>> {
req: IncomingMessage {
_readableState: ReadableState {
objectMode: false,
highWaterMark: 16384,
buffer: BufferList { head: null, tail: null, length: 0 },
length: 0,
pipes: [],
flowing: null,
ended: true,
endEmitted: false,
reading: false,
sync: true,
needReadable: false,
emittedReadable: false,
readableListening: false,
resumeScheduled: false,
errorEmitted: false,
emitClose: true,
autoDestroy: false,
destroyed: false,
errored: null,
closed: false,
closeEmitted: false,
defaultEncoding: 'utf8',
awaitDrainWriters: null,
multiAwaitDrain: false,
readingMore: true,
decoder: null,
encoding: null,
[Symbol(kPaused)]: null
},
_events: [Object: null prototype] { end: [Function: clearRequestTimeout] },
_eventsCount: 1,
_maxListeners: undefined,
socket: Socket {
connecting: false,
_hadError: false,
_parent: null,
_host: null,
_readableState: [ReadableState],
_events: [Object: null prototype],
_eventsCount: 8,
_maxListeners: undefined,
_writableState: [WritableState],
allowHalfOpen: true,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: [Server],
_server: [Server],
parser: [HTTPParser],
on: [Function: socketListenerWrap],
addListener: [Function: socketListenerWrap],
prependListener: [Function: socketListenerWrap],
_paused: false,
_httpMessage: [ServerResponse],
timeout: 0,
[Symbol(async_id_symbol)]: 285916,
[Symbol(kHandle)]: [TCP],
[Symbol(kSetNoDelay)]: false,
[Symbol(lastWriteQueueSize)]: 0,
[Symbol(timeout)]: Timeout {
_idleTimeout: -1,
_idlePrev: null,
_idleNext: null,
_idleStart: 24100466,
_onTimeout: null,
_timerArgs: undefined,
_repeat: null,
_destroyed: true,
[Symbol(refed)]: false,
[Symbol(kHasPrimitive)]: false,
[Symbol(asyncId)]: 290206,
[Symbol(triggerId)]: 290203
},
[Symbol(kBuffer)]: null,
[Symbol(kBufferCb)]: null,
[Symbol(kBufferGen)]: null,
[Symbol(kCapture)]: false,
[Symbol(kBytesRead)]: 0,
[Symbol(kBytesWritten)]: 0,
[Symbol(RequestTimeout)]: undefined
},
httpVersionMajor: 1,
httpVersionMinor: 1,
httpVersion: '1.1',
complete: true,
headers: {
host: 'localhost:3000',
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:88.0) Gecko/20100101 Firefox/88.0',
accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'accept-language': 'fr,fr-FR;q=0.8,en-US;q=0.5,en;q=0.3',
'accept-encoding': 'gzip, deflate',
referer: 'http://localhost:3000/explore_clientSide',
dnt: '1',
connection: 'keep-alive',
'upgrade-insecure-requests': '1',
'sec-gpc': '1'
},
rawHeaders: [
'Host',
'localhost:3000',
'User-Agent',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:88.0) Gecko/20100101 Firefox/88.0',
'Accept',
'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Language',
'fr,fr-FR;q=0.8,en-US;q=0.5,en;q=0.3',
'Accept-Encoding',
'gzip, deflate',
'Referer',
'http://localhost:3000/explore_clientSide',
'DNT',
'1',
'Connection',
'keep-alive',
'Upgrade-Insecure-Requests',
'1',
'Sec-GPC',
'1'
],
trailers: {},
rawTrailers: [],
aborted: false,
upgrade: false,
url: '/explore_SSR',
method: 'GET',
statusCode: null,
statusMessage: null,
client: Socket {
connecting: false,
_hadError: false,
_parent: null,
_host: null,
_readableState: [ReadableState],
_events: [Object: null prototype],
_eventsCount: 8,
_maxListeners: undefined,
_writableState: [WritableState],
allowHalfOpen: true,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: [Server],
_server: [Server],
parser: [HTTPParser],
on: [Function: socketListenerWrap],
addListener: [Function: socketListenerWrap],
prependListener: [Function: socketListenerWrap],
_paused: false,
_httpMessage: [ServerResponse],
timeout: 0,
[Symbol(async_id_symbol)]: 285916,
[Symbol(kHandle)]: [TCP],
[Symbol(kSetNoDelay)]: false,
[Symbol(lastWriteQueueSize)]: 0,
[Symbol(timeout)]: Timeout {
_idleTimeout: -1,
_idlePrev: null,
_idleNext: null,
_idleStart: 24100466,
_onTimeout: null,
_timerArgs: undefined,
_repeat: null,
_destroyed: true,
[Symbol(refed)]: false,
[Symbol(kHasPrimitive)]: false,
[Symbol(asyncId)]: 290206,
[Symbol(triggerId)]: 290203
},
[Symbol(kBuffer)]: null,
[Symbol(kBufferCb)]: null,
[Symbol(kBufferGen)]: null,
[Symbol(kCapture)]: false,
[Symbol(kBytesRead)]: 0,
[Symbol(kBytesWritten)]: 0,
[Symbol(RequestTimeout)]: undefined
},
_consuming: false,
_dumped: false,
cookies: [Getter/Setter],
__NEXT_INIT_QUERY: {},
[Symbol(kCapture)]: false,
[Symbol(RequestTimeout)]: undefined
},
res: <ref *1> ServerResponse {
_events: [Object: null prototype] { finish: [Function: bound resOnFinish] },
_eventsCount: 1,
_maxListeners: undefined,
outputData: [],
outputSize: 0,
writable: true,
destroyed: false,
_last: false,
chunkedEncoding: false,
shouldKeepAlive: true,
_defaultKeepAlive: true,
useChunkedEncodingByDefault: true,
sendDate: true,
_removedConnection: false,
_removedContLen: false,
_removedTE: false,
_contentLength: null,
_hasBody: true,
_trailer: '',
finished: false,
_headerSent: false,
socket: Socket {
connecting: false,
_hadError: false,
_parent: null,
_host: null,
_readableState: [ReadableState],
_events: [Object: null prototype],
_eventsCount: 8,
_maxListeners: undefined,
_writableState: [WritableState],
allowHalfOpen: true,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: [Server],
_server: [Server],
parser: [HTTPParser],
on: [Function: socketListenerWrap],
addListener: [Function: socketListenerWrap],
prependListener: [Function: socketListenerWrap],
_paused: false,
_httpMessage: [Circular *1],
timeout: 0,
[Symbol(async_id_symbol)]: 285916,
[Symbol(kHandle)]: [TCP],
[Symbol(kSetNoDelay)]: false,
[Symbol(lastWriteQueueSize)]: 0,
[Symbol(timeout)]: Timeout {
_idleTimeout: -1,
_idlePrev: null,
_idleNext: null,
_idleStart: 24100466,
_onTimeout: null,
_timerArgs: undefined,
_repeat: null,
_destroyed: true,
[Symbol(refed)]: false,
[Symbol(kHasPrimitive)]: false,
[Symbol(asyncId)]: 290206,
[Symbol(triggerId)]: 290203
},
[Symbol(kBuffer)]: null,
[Symbol(kBufferCb)]: null,
[Symbol(kBufferGen)]: null,
[Symbol(kCapture)]: false,
[Symbol(kBytesRead)]: 0,
[Symbol(kBytesWritten)]: 0,
[Symbol(RequestTimeout)]: undefined
},
_header: null,
_keepAliveTimeout: 5000,
_onPendingData: [Function: bound updateOutgoingData],
_sent100: false,
_expect_continue: false,
statusCode: 200,
flush: [Function: flush],
write: [Function: write],
end: [Function: end],
on: [Function: on],
writeHead: [Function: writeHead],
[Symbol(kCapture)]: false,
[Symbol(kNeedDrain)]: false,
[Symbol(corked)]: 0,
[Symbol(kOutHeaders)]: null
},
query: {},
resolvedUrl: '/explore_SSR',
locales: undefined,
locale: undefined,
defaultLocale: undefined,
db: {
client: MongoClient {
_events: [Object: null prototype],
_eventsCount: 1,
_maxListeners: undefined,
s: [Object],
topology: [NativeTopology],
[Symbol(kCapture)]: false
},
db: Db {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
s: [Object],
serverConfig: [Getter],
bufferMaxEntries: [Getter],
databaseName: [Getter],
[Symbol(kCapture)]: false
}
}
}
But it's not working for me. The _context of my resolver is still undefined.
(console.log in apollo/resolvers.js: _context :>> undefined)
Maybe we cannot use Apollo and Database connection with the API route and Server side rendering mode or i just missing something big.
Any idea of how i could implement the Mongodb database connection to have acces to it from my resolver in any kind of rendering mode?

Puppeteer on Raspberry Pi fails to start chromium-browser: Error: read ECONNRESET

I am trying to run puppeteer on a Raspberry Pi 4 with Ubuntu installed.
const puppeteer = require('puppeteer');
async function configureBrowser() {
// error here
var browser1 = await puppeteer.launch({ headless: true, executablePath: '/usr/bin/chromium-browser', args: ['--no-sandbox', '--disable-setuid-sandbox'] });
const page = await browser.newPage();
await page.goto('www.google.com');
return page;
}
async function monitor() {
let page = await configureBrowser();
}
monitor().catch(error => { console.error("Something bad happened...", error); });
It produces the error below from the chromium-browser. Does anyone know what this means? I have tried installing extra dependencies and various options for the browser launch, but nothing yet works. It is a Raspberry Pi 4 that I ssh into.
(node:2870) ExperimentalWarning: The fs.promises API is experimental
Something bad happened... ErrorEvent {
target:
WebSocket {
_events:
[Object: null prototype] { open: [Function], error: [Function] },
_eventsCount: 2,
_maxListeners: undefined,
_binaryType: 'nodebuffer',
_closeCode: 1006,
_closeFrameReceived: false,
_closeFrameSent: false,
_closeMessage: '',
_closeTimer: null,
_extensions: {},
_protocol: '',
_readyState: 3,
_receiver: null,
_sender: null,
_socket: null,
_bufferedAmount: 0,
_isServer: false,
_redirects: 0,
_url:
'ws://127.0.0.1:35593/devtools/browser/b4694718-7829-4f29-945a-1a16d20455a8',
_req: null },
type: 'error',
message: 'read ECONNRESET',
error:
{ Error: read ECONNRESET
at TCP.onStreamRead (internal/stream_base_commons.js:111:27) errno: 'ECONNRESET', code: 'ECONNRESET', syscall: 'read' } }

Do I need to connect to Mongo over and over again?

I am making a discord bot. When I was using java, I saved the data to mongo by creating different databases for each server my bot is in but on javascript I can only use one database.
And the only database it lets me connect/see is test database, other than that it shows everything as undefined.
And Mongo js docs tell me to connect to database over and over again but when using java I just connected on bot launch and was able to use it whenever I want. I tried all the examples I could find on stackoverflow but none of them helped me at all.
app.js :
require("./handler/mongo")();
client.on("ready", () => {
console.log(global.mongoclient.db("574612262275252231").collection("settings").find({}));
}
mongo.js:
const mongo = require('mongodb').MongoClient;
module.exports = function(){
mongo.connect(uri, (err, client) => {
if(err) throw err;
global.mongoclient = client;
console.log("a");
});
}
console output:
a
Cursor {
_readableState: ReadableState {
objectMode: true,
highWaterMark: 16,
buffer: BufferList { head: null, tail: null, length: 0 },
length: 0,
pipes: [],
flowing: null,
ended: false,
endEmitted: false,
reading: false,
sync: true,
needReadable: false,
emittedReadable: false,
readableListening: false,
resumeScheduled: false,
errorEmitted: false,
emitClose: true,
autoDestroy: false,
destroyed: false,
defaultEncoding: 'utf8',
awaitDrainWriters: null,
multiAwaitDrain: false,
readingMore: false,
decoder: null,
encoding: null,
[Symbol(kPaused)]: null
},
readable: true,
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
operation: FindOperation {
options: {
skip: 0,
limit: 0,
raw: undefined,
hint: null,
timeout: undefined,
slaveOk: true,
readPreference: [ReadPreference],
db: [Db],
promiseLibrary: [Function: Promise]
},
ns: MongoDBNamespace {
db: '574612262275252231',
collection: 'settings'
},
cmd: {
find: '574612262275252231.settings',
limit: 0,
skip: 0,
query: {},
raw: undefined,
hint: null,
timeout: undefined,
slaveOk: true,
readPreference: [ReadPreference]
},
readPreference: ReadPreference { mode: 'primary', tags: undefined },
cursorState: {
cursorId: null,
cmd: [Object],
documents: [],
cursorIndex: 0,
dead: false,
killed: false,
init: false,
notified: false,
limit: 0,
skip: 0,
batchSize: 1000,
currentLimit: 0,
transforms: undefined,
raw: undefined
}
},
pool: null,
server: null,
disconnectHandler: undefined,
bson: undefined,
ns: '574612262275252231.settings',
namespace: MongoDBNamespace { db: '574612262275252231', collection: 'settings' },
cmd: {
find: '574612262275252231.settings',
limit: 0,
skip: 0,
query: {},
raw: undefined,
hint: null,
timeout: undefined,
slaveOk: true,
readPreference: ReadPreference { mode: 'primary', tags: undefined }
},
options: {
skip: 0,
limit: 0,
raw: undefined,
hint: null,
timeout: undefined,
slaveOk: true,
readPreference: ReadPreference { mode: 'primary', tags: undefined },
db: Db {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
s: [Object],
serverConfig: [Getter],
bufferMaxEntries: [Getter],
databaseName: [Getter],
[Symbol(kCapture)]: false
},
promiseLibrary: [Function: Promise]
},
topology: ReplSet {
_events: [Object: null prototype] {
authenticated: [Function (anonymous)],
error: [Array],
timeout: [Array],
close: [Array],
parseError: [Array],
reconnect: [Array],
commandStarted: [Function (anonymous)],
commandSucceeded: [Function (anonymous)],
commandFailed: [Function (anonymous)],
serverOpening: [Function (anonymous)],
serverClosed: [Function (anonymous)],
serverDescriptionChanged: [Function (anonymous)],
serverHeartbeatStarted: [Function (anonymous)],
serverHeartbeatSucceeded: [Function (anonymous)],
serverHeartbeatFailed: [Function (anonymous)],
topologyOpening: [Function (anonymous)],
topologyClosed: [Function (anonymous)],
topologyDescriptionChanged: [Function (anonymous)],
joined: [Function (anonymous)],
left: [Function (anonymous)],
ping: [Function (anonymous)],
ha: [Function (anonymous)],
connectionPoolCreated: [Function (anonymous)],
connectionPoolClosed: [Function (anonymous)],
connectionCreated: [Function (anonymous)],
connectionReady: [Function (anonymous)],
connectionClosed: [Function (anonymous)],
connectionCheckOutStarted: [Function (anonymous)],
connectionCheckOutFailed: [Function (anonymous)],
connectionCheckedOut: [Function (anonymous)],
connectionCheckedIn: [Function (anonymous)],
connectionPoolCleared: [Function (anonymous)],
open: [Function],
fullsetup: [Function],
all: [Function]
},
_eventsCount: 35,
_maxListeners: Infinity,
s: {
coreTopology: [ReplSet],
sCapabilities: [ServerCapabilities],
tag: undefined,
storeOptions: [Object],
clonedOptions: [Object],
store: [Store],
options: [Object],
sessionPool: [ServerSessionPool],
sessions: Set(0) {},
promiseLibrary: [Function: Promise]
},
[Symbol(kCapture)]: false
},
cursorState: {
cursorId: null,
cmd: {
find: '574612262275252231.settings',
limit: 0,
skip: 0,
query: {},
raw: undefined,
hint: null,
timeout: undefined,
slaveOk: true,
readPreference: [ReadPreference]
},
documents: [],
cursorIndex: 0,
dead: false,
killed: false,
init: false,
notified: false,
limit: 0,
skip: 0,
batchSize: 1000,
currentLimit: 0,
transforms: undefined,
raw: undefined
},
logger: Logger { className: 'Cursor' },
s: {
numberOfRetries: 5,
tailableRetryInterval: 500,
currentNumberOfRetries: 5,
state: 0,
promiseLibrary: [Function: Promise],
explicitlyIgnoreSession: false
},
[Symbol(kCapture)]: false
}
And Mongo js docs tell me to connect to database over and over again
Those are simply examples. You can have a global client if you like (which would make sense for real applications).

Nuxt.js socket hang up on axios get only on https not http server

I'm using Nuxt 2.8.1, Axios Module (https://axios.nuxtjs.org).
I followed up this guide https://nuxtjs.org/faq/http-proxy/ to solve CORS problems on Firefox/IE, but ended up NuxtServerError: socket hang up on every proxied request if I ENABLE server https option in nuxt.config.js, not if I disable.
I tried adding rejectUnauthorized: false to server https param, wrote an express server to handle the SSL certificate and render using Nuxt,... but still can't solve the problem.
This is my nuxt.config.js:
env: {
API_HOST: 'https://api.mywebsite.com',
BASE_URL: process.env.BASE_URL || 'http://localhost:3000',
},
axios: {
proxy: true,
},
proxy: {
'/api/': {
target: 'https://api.mywebsite.com/api',
pathRewrite: {'/api': ''},
credentials: false,
}
},
server: {
port: 3000,
https: {
rejectUnauthorized: false,
key: fs.readFileSync('../privkey.pem'),
cert: fs.readFileSync('../fullchain.pem')
}
}
It works well if i just remove whole https param in 'server'. Here is my axios call on store/index.js:
export const actions = {
async nuxtServerInit ( { commit } ) {
const { data } = await this.$axios.get('/api/option');
let options = {};
data.forEach(item => {
options[item.Name] = item.Value;
});
commit('setOptions', options)
},
}
This is my console log on that axios call:
Promise { 18:04:38
<rejected> [Error: socket hang up] {
at createHangUpError (_http_client.js:323:15)
at Socket.socketOnEnd (_http_client.js:426:23)
at Socket.emit (events.js:203:15)
at Socket.EventEmitter.emit (domain.js:448:20)
at endReadableNT (_stream_readable.js:1129:12)
at process._tickCallback (internal/process/next_tick.js:63:19)
code: 'ECONNRESET',
config: {
url: 'http://localhost:3000/api/option',
method: 'get',
headers: [Object],
baseURL: 'http://localhost:3000/',
transformRequest: [Array],
transformResponse: [Array],
timeout: 0,
adapter: [Function: httpAdapter],
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
validateStatus: [Function: validateStatus],
data: undefined
},
request: Writable {
_writableState: [WritableState],
writable: true,
domain: null,
_events: [Object],
_eventsCount: 2,
_maxListeners: undefined,
_options: [Object],
_redirectCount: 0,
_redirects: [],
_requestBodyLength: 0,
_requestBodyBuffers: [],
_onNativeResponse: [Function],
_currentRequest: [ClientRequest],
_currentUrl: 'http://localhost:3000/api/option'
},
response: undefined,
isAxiosError: true,
toJSON: [Function]
}
}
I would appreciate any help :)
I tried to use as many options as I thought was relevant in the proxy module, but ended up nowhere. I think you should create an issue on either #nuxtjs/proxy or on http-proxy-middleware github.
On my end the proxy route works without a problem with Vue's normal lifecycles, but will end up with a socket hang up when placed in asyncData or fetch - so I assume it's a SSR issue.
I don't have any problems with CORS, so I ended up creating module clones of the axios-module with custom prototypes. This setup unfortunately doesn't work alongside the axios-module as that also creates a socket hangup regardless of whether I have a proxy setup.
https://stackoverflow.com/a/43439886/1989083
I fixed my same issue by adding these lines into axios.js:
delete process.env['http_proxy'];
delete process.env['HTTP_PROXY'];
delete process.env['https_proxy'];
delete process.env['HTTPS_PROXY'];

Can make post request to localhost using node-fetch, but unable to do so using Axios

I have tried making the same post request using node-fetch and axios.
var fetch = require('node-fetch');
var axios = require('axios');
async function fetchTest(host, port, body) {
const response = {
successMessage: '',
errorMessage: ''
}
try {
const streamResponse = await fetch(`${host}:${port}`, {
method: 'post',
body: JSON.stringify(body)
})
const jsonResponse = await streamResponse.json()
response.successMessage = jsonResponse;
} catch (error) {
response.errorMessage = error;
}
return response;
}
async function axiosTest(host, port, body) {
const response = {
successMessage: '',
errorMessage: ''
}
try {
const jsonResponse = await axios({
method: 'post',
url: `${host}:${port}`,
data: body
})
response.successMessage = jsonResponse;
} catch (error) {
response.errorMessage = error;
}
return response;
}
async function test() {
console.log(await fetchTest('http://127.0.0.1', '8801', { type: 'request', cmd: 'devices' }));
console.log(await axiosTest('http://127.0.0.1', '8801', { type: 'request', cmd: 'devices' }));
}
test();
The request made with node-fetch works nicely. The request made with axios returns (IP address redacted with ...) an error:
{ successMessage: '',
errorMessage:
{ Error: connect ECONNREFUSED ...:80
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1161:14)
errno: 'ECONNREFUSED',
code: 'ECONNREFUSED',
syscall: 'connect',
address: '...',
port: 80,
config:
{ adapter: [Function: httpAdapter],
transformRequest: [Object],
transformResponse: [Object],
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
validateStatus: [Function: validateStatus],
headers: [Object],
method: 'post',
url: 'http://127.0.0.1:8801',
data: '{"type":"request","cmd":"devices"}' },
request:
Writable {
_writableState: [WritableState],
writable: true,
_events: [Object],
_eventsCount: 2,
_maxListeners: undefined,
_options: [Object],
_redirectCount: 1,
_redirects: [],
_requestBodyLength: 39,
_requestBodyBuffers: [],
_onNativeResponse: [Function],
_currentRequest: [ClientRequest],
_currentUrl: 'http://.../',
_isRedirect: true },
response: undefined } }
What might be the reason? Am I doing something wrong?
EDITED with more info requested in comment:
The axios request fails the same way if I comment out the node-fetch request.
The node-fetch request returns:
{
cmd: 'devices',
payload: { devices: [Array] },
type: 'response' },
}
Since I wrap the result in a response object, the console.log looks like
{
successMessage:
{
cmd: 'devices',
payload: { devices: [Array] },
type: 'response'
},
errorMessage: ''
}