Fetch error when refreshing page with await block in SvelteKit - node.js

I am building a sveltekit app that crashes when I refresh the page. Below is the code for the Home page that displays a map with points. The points are fetched from an api (also running on localhost). I initially had the await call inside an onMount function (worked fine) but I thought it would be tidier to use an await block. When the app is running everything works great - I can navigate to and from the Home page and the map loads as expected. However, if I refresh the browser on the Home page or navigate directly to the Home page after starting the app it crashes.
Update:
I now realize that using an await block or sveltkit's load function will run the fetch function on the server side before the page loads. This appears to fail because the map component relies on window. Disabling SSR fixes the issue although I would expect that the data object could be fetched via a load function and this not interfere with component creation, i.e. SSR shouldn't need to be disabled.
Svelte page:
<script>
const API_PATH = import.meta.env.VITE_API_PATH;
import Map from '$lib/Leaflet/Map.svelte';
import Point from '$lib/Leaflet/Vector/Point.svelte';
const lat = -41.273;
const lng = 173.279;
const zoom = 15;
async function getSites() {
const res = await fetch(API_PATH + '/sites');
const sites = await res.json();
if (res.ok) {
return sites;
} else {
throw new Error(sites);
}
}
let promise = getSites();
</script>
<svelte:head>
<title>Home</title>
</svelte:head>
<main>
<Map center={[lat, lng]} {zoom}>
{#await promise then sites}
{#each Object.values(sites['features']) as site}
<Point lat={site['geometry']['coordinates'][1]} lng={site['geometry']['coordinates'][0]}>
</Point>
{/each}
{/await}
</Map>
</main>
I get the following error in terminal:
Got request /
file:///.../node_modules/#sveltejs/kit/dist/install-fetch.js:6246
reject(new FetchError(`request to ${request.url} failed, reason: ${error.message}`, 'system', error));
^
FetchError: request to http://localhost:8000/sites failed, reason: connect ECONNREFUSED ::1:8000
at ClientRequest.<anonymous> (file:///.../node_modules/#sveltejs/kit/dist/install-fetch.js:6246:11)
at ClientRequest.emit (node:events:520:28)
at Socket.socketErrorListener (node:_http_client:442:9)
at Socket.emit (node:events:520:28)
at emitErrorNT (node:internal/streams/destroy:164:8)
at emitErrorCloseNT (node:internal/streams/destroy:129:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
type: 'system',
errno: 'ECONNREFUSED',
code: 'ECONNREFUSED',
erroredSysCall: 'connect'
}
And in the browser console:
Loading failed for the module with source “http://localhost:3000/#fs/.../.svelte-kit/runtime/client/start.js”.
Thanks for the support.

Related

node-fetch even though server is online it keeps saying errconrefused

Connecting to the server through browser is possible and i get http code 200, I have directly copied the url from the browser to the node fetch:
await fetch(`http://localhost:9000/renderAvatar.3d?pant=http://localhost/assets/2.png&face=http://localhost/assets/0.png&shirt=http://localhost/assets/1.png&name=de&trick=e`)
The other server on the 9000 port is written in c# and has code like this:
HttpListener httpServer;
public void SomeFunction() {
//Some boilerplate for http server definitely not stolen amogus
httpServer = new HttpListener();
httpServer.Prefixes.Add("http://localhost:9000/");
httpServer.Start();
Task demo = Server();
demo.GetAwaiter().GetResult();
}
public async Task server() {
while(true) {
HttpListenerContext ctx = await httpServer.GetContextAsync();
HttpListenerRequest req = ctx.Request;
HttpListenerResponse resp = ctx.Response;
if(req.HttpMethod == "GET") {
if(req.Url.AbsolutePath.ToString() == "/renderAvatar.3d") {
var parameters = HttpUtility.ParseQueryString(req.Url.Query);
if(parameters.Count > 3) {
var pant = parameters[0].ToString();
var face = parameters[1].ToString();
var shirt = parameters[2].ToString();
var name = parameters[3].ToString();
// can't share more code due this is propertiary code
any access from the browser works but why node fetch doesn't work, i have very bad solution to this issue using chrome to open up avatar renderer then close the chrome programatically but this uses way too much memory and quite unncesary.
(This is on linux btw, port 9000 shouldn't be protected by firewall and this is a local server)
thrown error:
FetchError: request to http://127.0.0.1:9000/renderAvatar.3d?pant=http://localhost/assets/2.png&face=http://localhost/assets/0.png&shirt=http://localhost/assets/1.png&name=de&trick=e failed, reason: connect ECONNREFUSED 127.0.0.1:9000
at ClientRequest.<anonymous> (file:///home/
(confidental)/backend/node_modules/node-fetch/src/index.js:108:11)
at ClientRequest.emit (node:events:527:28)
at Socket.socketErrorListener (node:_http_client:454:9)
at Socket.emit (node:events:527:28)
at emitErrorNT (node:internal/streams/destroy:157:8)
at emitErrorCloseNT (node:internal/streams/destroy:122:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
type: 'system',
errno: 'ECONNREFUSED',
code: 'ECONNREFUSED',
erroredSysCall: 'connect'
}
Turns out changing localhost to 127.0.0.1 on the c# app solves the issue, on linux localhost is automatically converted to 127.0.0.1 but c# app doesn't do that for some odd reason.
httpServer.Prefixes.Add("http://localhost:9000/");
to
httpServer.Prefixes.Add("http://127.0.0.1:9000/");

process.env["NODE_TLS_REJECT_UNAUTHORIZED"] = 0 not working

I'm using the node sendmail package which is giving me this error:
Error on connectMx for: Error: self signed certificate
at TLSSocket.onConnectSecure (_tls_wrap.js:1515:34)
at TLSSocket.emit (events.js:400:28)
at TLSSocket._finishInit (_tls_wrap.js:937:8)
at TLSWrap.ssl.onhandshakedone (_tls_wrap.js:709:12) {
code: 'DEPTH_ZERO_SELF_SIGNED_CERT'
}
So I put this in my code in like 5 places
process.env["NODE_TLS_REJECT_UNAUTHORIZED"] = 0;
Node says this warning when I run it:
Warning: Setting the NODE_TLS_REJECT_UNAUTHORIZED environment variable to '0' makes TLS connections and HTTPS requests insecure by disabling certificate verification.
Yet I still get the error message. It's coming from this code:
const {createConnection} = require('net');
createConnection(smtpPort, data[i].exchange); // problem code
sock.on('error', function (err) {
logger.error('Error on connectMx for: ', data[i], err);
tryConnect(++i)
});
Is this a bug in NodeJS, or am I messing something up? Thanks for the help.

Error when attempting to PUT file to URL with Node request

I am trying to PUT a file to an S3 pre-signed URL. Doing so with bash/cURL works fine but with Node I am getting the following error:
Error: write EPIPE
at WriteWrap.onWriteComplete [as oncomplete] (node:internal/stream_base_commons:94:16) {
errno: -32,
code: 'EPIPE',
syscall: 'write'
}
Here is the code
const fs = require('fs');
const request = require('request');
stream = fs.createReadStream('/tmp/file');
r = request.put('https://s3.eu-west-2.amazonaws.com/bucketname/path?X-Amz-Content-Sha256=....&...');
stream.pipe(r).on('error', function(err) {
console.log(err);
});
EPIPE means that the writing request failed because the other end closed the connection. Looks like there might be some additional settings required inorder to work with amazon s3. I know that curl has native support for multipart/form-data. You can use this library to create readable multipart/form-data streams.
https://nicedoc.io/form-data/form-data
Or you can use third party libraries to send data
https://www.npmjs.com/package/s3-upload-stream
https://www.npmjs.com/package/streaming-s3

Server side rendering with Apollo: getaddrinfo ENOTFOUND

I'm running Apollo/React with Express and I'm trying to get server side rendering to work. The Apollo docs suggest the following initialisation code for connecting to the API server:
app.use((req, res) => {
match({ routes, location: req.originalUrl }, (error, redirectLocation, renderProps) => {
const client = new ApolloClient({
ssrMode: true,
networkInterface: createNetworkInterface({
uri: 'http://localhost:3000', // Instead of 3010
opts: {
credentials: 'same-origin',
headers: {
cookie: req.header('Cookie'),
},
},
}),
});
const app = (
<ApolloProvider client={client}>
<RouterContext {...renderProps} />
</ApolloProvider>
);
getDataFromTree(app).then(() => {
const content = ReactDOM.renderToString(app);
const initialState = {[client.reduxRootKey]: client.getInitialState() };
const html = <Html content={content} state={initialState} />;
res.status(200);
res.send(`<!doctype html>\n${ReactDOM.renderToStaticMarkup(html)}`);
res.end();
});
});
});
which uses the match() function from React Router v3 (as evidenced by package.json in the "GitHunt" example linked from the docs). I'm using React Router v4 from which match() is absent, so I refactored the code as follows, using renderRoutes() from the react-router-config package.
app.use((req, res) => {
const client = new ApolloClient(/* Same as above */)
const context = {}
const app = (
<ApolloProvider client={client}>
<StaticRouter context={context} location={req.originalUrl}>
{ renderRoutes(routes) }
</StaticRouter>
</ApolloProvider>
)
getDataFromTree(app).then(/* Same as above */)
})
My understanding is that <StaticRouter> obviates the use of match(). However react-router-config provides a matchRoutes() function which seems to provide a similar functionality (albeit without the callback) if needed.
When I visit http://localhost:3000, the page loads as expected and I can follow links to subdirectories (e.g. http://localhost:3000/folder). When I try to directly load a subdirectory by typing in the name in the address bar, my browser keeps waiting for the server to respond. After about six seconds, Terminal shows one of the following errors (not sure what causes the error to change on subsequent tries):
(node:1938) UnhandledPromiseRejectionWarning: Unhandled promise
rejection (rejection id: 1): Error: Network error: request to
http://localhost:3000 failed, reason: getaddrinfo ENOTFOUND localhost
localhost:3000
or
(node:8691) UnhandledPromiseRejectionWarning: Unhandled promise
rejection (rejection id: 1): Error: Network error: request to
http://localhost:3000 failed, reason: socket hang up
I've been struggling with this problem for a few hours now, but can't seem to figure it out. The solution to a similar problem seems unrelated to this case. Any help will be much appreciated!
Further information
If I don't kill the nodemon server, after some time I get thousands of the following errors:
POST / - - ms - -
(node:1938) UnhandledPromiseRejectionWarning:
Unhandled promise rejection (rejection id: 4443): Error: Network
error: request to http://localhost:3000 failed, reason: socket hang up
If I do kill the server, however, I immediately get this error instead:
/Users/.../node_modules/duplexer/index.js:31
writer.on("drain", function() {
^
TypeError: Cannot read property 'on' of undefined
at duplex (/Users/.../node_modules/duplexer/index.js:31:11)
at Object.module.exports (/Users/.../node_modules/stream-combiner/index.js:8:17)
at childrenOfPid (/Users/.../node_modules/ps-tree/index.js:50:6)
at kill (/Users/.../node_modules/nodemon/lib/monitor/run.js:271:7)
at Bus.onQuit (/Users/.../node_modules/nodemon/lib/monitor/run.js:327:5)
at emitNone (events.js:91:20)
at Bus.emit (events.js:188:7)
at process. (/Users/.../node_modules/nodemon/lib/monitor/run.js:349:9)
at Object.onceWrapper (events.js:293:19)
at emitNone (events.js:86:13)
Also, port 3000 is correct. If I change the number, I get a different error instead:
(node:2056) UnhandledPromiseRejectionWarning: Unhandled promise
rejection (rejection id: 1): Error: Network error: request to
http://localhost:3010 failed, reason: connect ECONNREFUSED
127.0.0.1:3010
Are you running your server / project inside a container / containers. I had the same issue as this and ended up doing the following to fix it.
const networkInterface = createNetworkInterface({
uri: process.browser
? 'http://0.0.0.0:1111/graphql'
: 'http://my-docker-container-name:8080/graphql'
})
I have an internal docker network created for my containers in my docker-compose.yml, which allows the containers to communicate with each other, however the browser communicates to the GQL server on a different URL, causing the issue you described on SSR the getaddrinfo ENOTFOUND, so although it was working client side, on the SSR it would fail.
I am using nextJS framework which gives the ability to detect the browser or SSR, i'm sure you could do the same outside of nextJS.
I finally found out that the error was due to renderToString and renderToStaticMarkup not being made available by importing ReactDOM.
The import statement import ReactDOM from 'react-dom' had to be replaced by import ReactDOMServer from 'react-dom/server'.
Also, uri had to point to http://localhost:3000/graphql instead of http://localhost:3000.

Error with ntwitter module for node.js

I'm trying to build a Twitter streaming app using node.js and the ntwitter module, here's my code :
var app = require('express').createServer(),
twitter=require('ntwitter');
app.listen(3000);
var feed = new twitter({
consumer_key: 'MY KEY',
consumer_secret:'MY SECRET KEY',
access_tocken_key:'MY ACCESS TOCKEN KEY',
access_tocken_secret:'MY ACCESS TOCKEN SECRET'
});
feed.stream('statuses/filter',{track: ['love', 'hate']}, function(stream){
stream.on('data',function(tweet){
console.log(tweet.text);
});
});
But here's what I get :
events.js:74
throw TypeError('Uncaught, unspecified "error" event.');
^
TypeError: Uncaught, unspecified "error" event.
at TypeError (<anonymous>)
at EventEmitter.emit (events.js:74:15)
at ClientRequest.<anonymous> (/Users/maximeheckel/Documents/My_Repositories/nodetwitter/node_modules/ntwitter/lib/twitter.js:251:14)
at ClientRequest.EventEmitter.emit (events.js:95:17)
at HTTPParser.parserOnIncomingClient [as onIncoming] (http.js:1628:21)
at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:119:23)
at CleartextStream.socketOnData [as ondata] (http.js:1523:20)
at CleartextStream.read [as _read] (tls.js:470:10)
at CleartextStream.Readable.read (_stream_readable.js:294:10)
at EncryptedStream.write [as _write] (tls.js:344:25)
I don't understand why I'm stuck with that as I'm following very carefully a lot of tutorials. Even when I clone the authors project I'm still getting this error.
Hope you can help.
UPDATE : I added
stream.on('error', function(error, code) {
console.log("My error: " + error + ": " + code);
});
To my stream function and I'm getting a HTTP 401 error
Any ideas ?
Everything with your code looks fine except for the spelling of "token" in the parameters passed to the constructor for twitter. You need to change access_tocken_key to access_token_key and access_tocken_secret to access_token_secret. Your error (401) is an authentication issue; that change should hopefully result in ntwitter passing the correct user authentication details to the Twitter API.
I had the same problem and it was because my servers system clock had floated by six minutes. Usually, API's give you about a five minute margin of error.

Resources