Websockets, truffle, ganache and react setup issues connection not open on send() - web3js

Sometimes I refresh, and it works. Sometimes it just doesn't work.
I tried changing ganache GUI settings to use port 8545 which I read is the WebSockets port but it still won't connect. ws:127.0.0.1 won't work and neither will http://
This is my truffle config file. The rest of the code is large and won't help much.
// See <http://truffleframework.com/docs/advanced/configuration>
// #truffle/hdwallet-provider
// var HDWalletProvider = require("truffle-hdwallet-provider");
const path = require("path");
var HDWalletProvider = require("#truffle/hdwallet-provider");
module.exports = {
// See <http://truffleframework.com/docs/advanced/configuration>
// to customize your Truffle configuration!
// contracts_directory: "./allMyStuff/someStuff/theContractFolder",
contracts_build_directory: path.join(__dirname, "/_truffle/build/contracts"),
// migrations_directory: "./allMyStuff/someStuff/theMigrationsFolder",
networks: {
ganache: {
host: "127.0.0.1",
port: 7545,
//port: 8545,
network_id: 5777,
//network_id: "*", // Match any network id,
websockets: false, // websockets true breaks TODO: connection not open on send()
// wss
},
},
};
This is some of my code on the actual screen in question.
const options = {
web3: {
block: false,
fallback: {
type: 'ws',
//url: 'ws://127.0.0.1:8546',
url: 'http://127.0.0.1:7545',
},
},
contracts: [MyStringStore],
// polls: {
// accounts: IntervalInMilliseconds,
// },
events: {},
};
I don't understand why sometimes it works and I can see drizzle state and sometimes I can't. React native and web3 is very new to me.
I get errors like this:
00:06 Contract MyStringStore not found on network ID: undefined
Error fetching accounts:
00:06 connection not open

I am having real difficulty setting up drizzle as well. One thing I see is that your
url: 'http://127.0.0.1:7545',
For some reason Drizzle only works with 'ws' as the prefix for such a URL. I am trying to follow this guide by people who got it working.

I think websocket is only available in the command line version.
Try install and use ganache-cli instead of the gui version.

Related

localhost:3000 This site can’t be reached after installing http-proxy-middleware

I am building a newsletter sign-up form that uses .netlify-lambda to send my form submission to Mailchimp. I installed http-proxy-middleware to help the front end find the netlify-lambda folder. After writing the proxy setup code below my React start script stopped working. It appears the proxy setup below is interfering with localhost:3000.
My proxy setup looks like this
const proxy = require('http-proxy-middleware');
module.exports = function(app) {
console.log('Using proxy...')
app.use(proxy('/.netlify/functions/', {
target: 'http://localhost:9000/',
"pathRewrite": {
"^\\.netlify/functions": ""
}
}));
};
If the target is localhost:9000 why is it interfering with localhost:3000?
When I start my Lambda server it says: Lambda server is listening on 9000.
I am also getting this error when trying to compile my client app.
crbug/1173575, non-JS module files deprecated
Short answer (for #lachnroll and anyone who might be encountering the same problem):
Please use const { createProxyMiddleware } = require("http-proxy-middleware") and app.use(createProxyMiddleware('/.netlify/functions/' ...)...) , instead of using const proxy = require('http-proxy-middleware'); and app.use(proxy("/.netlify/functions/" ...)...) , it should work.
Long one:
I've come across the same "can't be reached" thing in a React project when using http-proxy-middleware(2.0.3), until I changed const proxy = require('http-proxy-middleware'); and proxy("/.netlify/functions/" ...) to const { createProxyMiddleware } = require("http-proxy-middleware"); and app.use(createProxyMiddleware('/.netlify/functions/' ...)...) , I think the proxy has been removed, see: https://github.com/chimurai/http-proxy-middleware#readme

Webpack dev server sockjs-node returns 404 error

I am running a simple Vue app with webpack that I created with the vue-cli. When I run the dev server wtih npm run serve, it shows several errors in the client console when using sockjs-node. I believe this module is used by webpack for hot reloading (HMR).
The first error is:
Access to XMLHttpRequest at 'http://192.168.1.4:8080/sockjs-node/info?t=1615330207390' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I can solve this in two ways by editing the devServer in my vue.config.js. The first method is by setting public: 'localhost:8080'; and the second is by setting headers: {'Access-Control-Allow-Origin': 'http://192.168.1.4:8080', 'Access-Control-Allow-Credentials': 'true'}.
In both cases, I then see the following two errors:
POST http://localhost:8080/sockjs-node/690/qvgqwbdo/xhr_streaming?t=1615330686134 404 (Not Found)
GET http://localhost:8080/sockjs-node/690/zympwfsc/eventsource 404 (Not Found)
How do I resolve these errors so that the hot reloader will connect?
In the function I set to devServer.before in my vue.config.js file, I created my own websockets using Socket.io on the same port as my devSever. When the function returned, the devServer could not use that port for websockets, so it failed to launch sockjs-node. Therefore, when the frontend client tried to connect to the devServer, the requests were going to my sockets, instead of the devServer sockets, and it was ignoring them. Hence the 404 errors.
Here is my original code:
// server.js
const { createServer } = require('http')
const io = require('socket.io')
const addSocketEvents = require('./socket-api')
const port = process.env.PORT || 8080
module.exports = {
port,
configure(app) {
// `app` is an instance of express
// add the websockets
const httpServer = createServer(app)
socket = io(httpServer, {
path: '/socket-api'
})
addSocketEvents(socket)
// starts the server
// cannot use app.listen() because that will not start the websockets
httpServer.listen(port)
}
}
// vue.config.js
const { port, configure } = require('./server')
module.exports = {
devServer: {
before: configure,
public: `localhost:${port}`,
},
}
To fix this issue, I needed to allow the devServer to use the original port for sockjs-node, and launch my sockets on a different port. However, because I need to use the same port in production (due to restrictions by my current hosting provider), I only want my sockets to use a different port when running the devServer. To do this, I simply created a different httpServer and launched it on a different port, then created a proxy in the devServer config for that port. In my configure function, I just check to see if it is running in dev or prod, and act accordingly.
My production server is a simple express instance which calls the same configure function after it is created. This allows me to put all my startup code in one place.
Here is my new code:
// server.js
const { createServer } = require('http')
const io = require('socket.io')
const addSocketEvents = require('./socket-api')
const port = process.env.PORT || 8080
const proxyPort = 8081
module.exports = {
port,
proxyPort,
configure(app) {
// `app` is an instance of express
// add the websockets
let httpServer, socketPort
if (process.env.NODE_ENV === 'development') {
httpServer = createServer()
socketPort = proxyPort
} else {
httpServer = createServer(app)
socketPort = port
}
// adds the socket-api to be used via websockets
socket = io(httpServer, {
path: '/socket-api'
})
addSocketEvents(socket)
// starts the server
httpServer.listen(socketPort)
}
}
// vue.config.js
const { port, configure } = require('./server')
module.exports = {
devServer: {
before: configure,
public: `localhost:${port}`,
proxy: {
'/socket-api': {
target: `http://localhost:${proxyPort}`,
ws: true
}
}
},
}

Got an error Invalid src prop ('here is a link') on `next/image`, hostname "localhost" is not configured under images in your `next.config.js`

I am using the Image component from Next.js (it's a new feature of Next.js). I've tried to give the source URL:
{`${API}/user/photo/${blog.postedBy.username}`}
But it shows me this error. I also make changes in my next.config.js as
module.exports = {
images: {
domains: ['localhost'],
},
}
but nothing works for me. Please help if you know anything about this.
const src = `${API}/user/photo/${blog.postedBy.username}`;
<Image loader={() => src} src={src} width={500} height={500}/>
Here, loader is a function that generates the URLs for your image. It appends a root domain to your provided src, and generates multiple URLs to request the image at different sizes. These multiple URLs are used in the automatic srcset generation, so that visitors to your site will be served an image that is the right size for their viewport.
Edit next.config.js :
module.exports = {
reactStrictMode: true,
images: {
domains: ['example.com'],
},
}
Yes, I finally got the answer. Make loader function to load it from the destination of the image.
const myLoader=({src})=>{
return `${API}/user/photo/${blog.postedBy.username}`;
}
Use this loader function the loader attribute of an Image tag.
<Image loader={myLoader} src={`${API}/user/photo/${blog.postedBy.username}`} width={500}
height={500}/>
This works for me perfectly
I had the same issue, You need to restart your dev server, you need to do that each time you make changes on your next.config.js file.
The API string should include the port. e.g. localhost:3001
There are a whole bunch of out-of-date answers here that suggest setting the domains key in next.config.js. As of Next 12.3.0 this is no longer correct; see: https://nextjs.org/docs/messages/next-image-unconfigured-host
Instead, one should use a remotePatterns property, which is a little more complicated than the old domains:
module.exports = {
images: {
remotePatterns: [
{
protocol: 'https',
hostname: 'example.com',
port: '',
pathname: '/account123/**',
},
],
},
}
Inside next.config.js file.
Add Image src domain name:
const nextConfig = {
reactStrictMode: true,
images : {
domains : ['sangw.in', 'localhost', 'picsum.photos'] // <== Domain name
}
}
module.exports = nextConfig
Adding 'localhost' in the domains array will fix the issue,
Unfortunately nextJS didn't refresh the server automatically after configuration file(next.config.js) change.
You have to restart the server manually to reflect the changes.
You can also try by set reactStrictMode value reactStrictMode: true,
here is the full export object
module.exports = {
reactStrictMode: true,
images: {
domains: [
"localhost",
process.env.WORDPRESS_API_URL.match(/(http(?:s)?:\/\/)(.*)/)[2], // Valid WP Image domain.
"2.gravatar.com",
"0.gravatar.com",
"secure.gravatar.com",
],
},
};
First of all add and restart the dev server.
domains: ['localhost']
And be sure to return the image link with http(s) protocole
image link with localhost:port/... is wrong , return as http://localhost/... ( or with https )
I've faced the same issue, and my domains were correct. Deleting .next and node_modules folders, and running yarn/npm install fixed the issue.
For me, in next.config.js,
/** #type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
images: {
domains: [ "abc.def.org", ]
},
}
module.exports = nextConfig
and then in my Image tag
<Image
unoptimized // for image caching, else error
src={profile.picture}
alt={profile.picture || "IMG"}
width={60}
height={60}
/>

How to run lighthouse for the homepage after login from puppeteer

I added two npm "#lhci/cli" and puppeteer.After that I added two config file
lighthouserc.js : config details are:
module.exports = {
ci: {
upload: {
target: 'temporary-public-storage'
},
collect: {
puppeteerScript: 'puppeteer-script.js',
chromePath: puppeteer.executablePath(),
url: ["https://myWebsite.com/abc"],
headful: true,
numberOfRuns: 1,
disableStorageReset: true,
setting: {
disableStorageReset: true
},
puppeteerLaunchOptions: {
slowMo: 20,
headless: false,
disableStorageReset: true
}
},
assert: {
assertions: {
'categories:performance': ['warn', { minScore: 1 }],
'categories:accessibility': ['error', { minScore: 0.5 }]
}
}
}
};
puppeteer-script.js
module.exports = async (browser, context) => {
await page.setDefaultNavigationTimeout(90000);
await page.goto(context.url);
await page.type('input[type=text]', 'abc');
await page.type('input[type=email]', 'abc#abc.com');
await page.type('input[type=password]', 'abc#100');
await page.click('[type="button"]');
await page.waitForNavigation({ waitUntil: "networkidle2" })
await page.close();
};
and in package.json I added script command as :
"test:lighthouse": "lhci autorun --collect.settings.chromeFlags='--no-sandbox'"
Now Login is working fine but I want to run the lighthouse for the url that I specified in lighthouserc.js (https://myWebsite.com/abc).
But after login it is trying to access the url and again login screen is coming and the lighthouse is measuring performance for the login page.
Is it possible to run lighthouse on url I specified in the config.Please assist me.
https://myWebsite.com/abc is my reactjs application
I do not have complete information on the workflow of your site but as mentioned in the configuration guide puppeteer script is run for each url mentioned in the lhci config file.
And after puppeteer script is ran, lighthouse will open URL. Now if your site is opening login page again, that its an issue with your app or configuration most likely. Either your app is not setting cookie correctly or login process is failing somehow, you will need to check that.
Also, as puppeteer script will be running for every url in the config, its good idea to not re-login if you already logged in once, check out this issue on Github.

Using constant/variable as webpack dev server proxy URL pattern

In our development server setup we use webpack-dev-server proxy setting to connect ot the APIs via middleware server. Time to time we have to change the middleware server settings and without changing the information in multiple places we would like to keep them in a single place.
Therefore we tried the following,
const MIDDLEWARE_SERVER = 'https://midlleware.server';
const MIDDLEWARE_RESOURCE = '/xyz';
const MIDDLEWARE_API_ENDPOINT = MIDDLEWARE_SERVER + MIDDLEWARE_RESOURCE + '/api';
devserver: {
proxy: {
MIDDLEWARE_RESOURCE : {
target: MIDDLEWARE_API_ENDPOINT;
pathRewrite: { MIDDLEWARE_RESOURCE: '' },
}
}
This doesn't work resulting with a 404 error because the URL pattern has not recognised (we checked by catching a onProxyReq event).
But if we replace the MIDDLEWARE_RESOURCE with '/xyz' in the proxy section it works.
it that a limitation in providing 'proxy' patterns?
Thanks
I was able to get it work by using [MIDDLEWARE_RESOURCE] notation. Like below
const MIDDLEWARE_SERVER = 'https://midlleware.server';
const MIDDLEWARE_RESOURCE = '/xyz';
const MIDDLEWARE_API_ENDPOINT = MIDDLEWARE_SERVER + MIDDLEWARE_RESOURCE + '/api';
devserver: {
proxy: {
[MIDDLEWARE_RESOURCE] : {
target: MIDDLEWARE_API_ENDPOINT;
pathRewrite: { MIDDLEWARE_RESOURCE: '' },
}
}

Resources