ECONNREFUSED error using webpack-dev-server in Motoko project - node.js

I created a motoko backend and added some JavaScript and HTML for the frontend. Now I would like to deploy my project using webpack.
After the successfull deployment I get the following error interacting with the frontend:
[webpack-dev-server] [HPM] Error occurred while proxying request localhost:8080/api/v2/status to http://localhost:8000/ [ECONNREFUSED] (https://nodejs.org/api/errors.html#errors_common_system_errors)
Reading the documentation the frontend should run on the server http://localhost:8080 and API request will be proxyed to the replica on port 8000.
If I open port 8000 it says:
Could not find a canister id to forward to.
So from my understanding, the frontend server runs and if he makes an API call (e.g. calling a function within my code) it proxys it to port 8000, but the service on this port is inactive.
The webpack.config.js config for the proxy:
// proxy /api to port 8000 during development
devServer: {
proxy: {
"/api": {
target: "http://localhost:8000",
changeOrigin: true,
pathRewrite: {
"^/api": "/api",
},
},
},
hot: true,
watchFiles: [path.resolve(__dirname, "src", frontendDirectory)],
liveReload: true,
},
};
UPDATE
I fixed the issue. The API calls where routed to the wrong adress. I changed it in the webpack.config.js to http://127.0.0.1:8000/.

I fixed the issue. The API calls where routed to the wrong adress. I changed it in the webpack.config.js to http://127.0.0.1:8000/.

Related

Add Node.js backend to React project?

So I have created a React app with
npx create-react-app my-app
and written a few functions and some content to my web app. Now I do need to implement backend for connecting to my SQL database and reading/writing from there. It is my understanding that server-side logic (NodeJS) and front-end code (React) should be in same repository, but how exactly is that done? I should probably create /backend folder and server.js inside it, but where? In the same folder with node_modules, public and src or elsewhere? Also, it would be nice to know more about how information exchange between Node and React works so I can display data fetched from database with React. Thanks in advance.
For development I have two folders on same level - src with react and server with node.
You start (e.g.)
nodejs server on port 5000
webpack-dev-server on port 3000
React communicates with backend via REST API. You have to proxy api requests to your server (part of webpack dev configuration):
devServer: {
contentBase: path.join(__dirname, 'server', 'static', 'public'),
port: 3000,
publicPath: 'http://localhost:3000/',
historyApiFallback: true,
disableHostCheck: true,
hot: true,
proxy: {
'/api': {
target: 'http://127.0.0.1:5000/',
},
},
},
In production environment the react is compiled to server/reactapp subfolder and served with expressjs as any other webpage.
Part of webpack production:
output: {
path: path.join(__dirname, 'server', 'reactapp'),
// publicPath: path.join('dist'),
filename: '[name].bundle.js',
publicPath: '/',
},
In Express (or any other web framework) you then serve the /api path with your backend tasks.
This all means I have two separated development environments - server and react, which partly join till in production environment. They both have separated package.json and node_modules.
In newer versions I have replaced REST API communication with websocket, what needs some other settings in communication.

Proxying HTTP requests in Angular 7

Previously I was using "proxy.conf.json" to proxy http requests in Angular which was working fine. Now I want to make the proxy urls dynamic, for which I have created a "proxy.conf.js" as mentioned in the Angular Wiki (https://github.com/angular/angular-cli/blob/master/docs/documentation/stories/proxy.md) and added the following:
const PROXY_CONFIG = [
{
context: [
"/api/*"
],
target: "https://example.com/",
logLevel: "debug",
secure: false,
changeOrigin: true
},
{
context: [
"/login/*"
],
target: "https://example1.com/",
logLevel: "debug",
secure: false,
changeOrigin: true
}
]
module.exports = PROXY_CONFIG;
And in the "package.json", I have added the following:
"start-dev": "ng serve --proxy-config proxy.conf.js",
But when I run this script "npm run start-dev", it does not read from the "proxy.conf.js" file although it says "Proxy created".
** Angular Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ **
10% building 3/3 modules 0 active[HPM] Proxy created: [ '/login/*' ] -> https://example1.com/
Instead of making http request to "https://example.com/", the url is still pointing to "http://localhost:4200/"
Could someone please let me know if there is anything I'm missing out here.
In your Proxy configuration the context pattern is /login/* however the actual request according to your console output is simply /login with no trailing component.
Therefore this proxy rule das not match and the dev server has no local resource for this and therefore answers with a 404.
You can either change the context or add a second entry for /login.

How to resolve invalid host header issue in webpack?

I'm getting invalid host header error, if i access my page through browser with online ip. Locally it is working perfectly, but i don't know why this error is coming in live server. I'm following three steps to run my react js application, that is,
'npm install'
'npm run build'
'npm run serve'
webpack config file host setup
// replace localhost with 0.0.0.0 if you want to access
// your app from wifi or a virtual machine
const host = process.env.HOST || '0.0.0.0';
const port = process.env.PORT || 3000;
const stats = {
hash: false,
version: false,
timings: false,
assets: false,
chunks: false,
modules: false,
reasons: false,
children: false,
source: false,
errors: false,
errorDetails: false,
warnings: false,
publicPath: false,
colors: {
green: '\u001b[32m',
},
};
package.json scripts
"build": "rimraf build && cross-env NODE_ENV=production webpack --env.prod=true --env.sw=true",
"serve": "pushstate-server build/ 3000",
Webpack dev server has recently had a host check added by default as a security measure https://github.com/webpack/webpack-dev-server/releases/tag/v2.4.3
You will now need to either disable it via disableHostCheck option (not wise if publicly accessible) or specify the public host or IP that you will be accessing it at when starting the server --public your-hostname-or-public-ip:3000
EDIT: Webpack in question name and webpack-dev-server tag was misleading - this actually uses different server altogether...
Ah it looks like this is not actually webpack related at all - you are using a different server pushstate-server which strangely has the host option in the module, but is not exposed in the binary. You will have to roll your own server startup script to pass a different host to it (it is 0.0.0.0 by default).
Save this to ./server.sh
#!/usr/bin/env node
require('pushstate-server').start({
directory: process.argv[2],
port: process.argv[3],
file: process.argv[4],
host: process.argv[5]
}, (err, address) =>
console.log(`Listening on port ${address.port} (http://${address.address}:${address.port})`)
)`
Change your npm script change to
server.sh build/ 3000 index.html your-publicly-accessible-hostname
I had the same error when I came across to these:
https://help.crossbrowsertesting.com/faqs/testing/invalid-host-header-error/
In my case it was solved by restarting the service.

React UI and Node.js/Express app served/monitored with webpack

I am new to React and Node, trying to setup an environment to work.
I worked a little with Node.js/Express before and I used nodemon to monitor file changes and restart my app.
Also I recently started to work with React and I use webpack dev server (specifically webpack-dev-server --content-base src --inline --hot --history-api-fallback) setup that monitors file changes and reload the UI.
The problem
Now, I want to tie it together.
First solution I found was: Start my node app on specific port, say 3000 then start webpack dev server on 8080 port and proxy requests to specific urls to my backend app.
devServer: {
proxy: {
'/backend-api/': {
target: {
"host": "localhost",
"protocol": 'http:',
"port": 3000
},
ignorePath: false,
changeOrigin: true,
secure: false
}
}
},
It should work but i do not feel right starting two servers for single application.
Is there any way (and simple example i could understand) to start single server that would serve both: a server side app and React UI?
And of course, it should track file changes and restart server app if server code changes OR reload UI if client side code changes.
You can use webpack through Express middleware using this package: https://github.com/webpack/webpack-dev-middleware
You can use it by simply adding it to the app:
var webpackMiddleware = require("webpack-dev-middleware");
app.use(webpackMiddleware(webpack({/* webpack options */})));
In addition there's a package that builds on this to offer hotloading and "Create React App" style terminal display: https://www.npmjs.com/package/webpack-express-middleware

How to setup a proxy using web sockets and angular CLI

I have a simple web app built using the angular CLI. I want it to communicate with a backend using web sockets. I have the backend already written and have tested with a simple index.html page that the server can send and receive on sockets.
In my angular-cli project I have setup a proxy config file to setup a proxy to the backend.
proxy.conf.json
{
"/sock": {
"target": "http://localhost:3000",
"changeOrigin": true,
"ws": true,
"logLevel": "debug"
}
}
Then start the server with the following.
ng serve --proxy-config proxy.conf.json
For now I have a service that simply attempts to open a socket and send a fixed string which I'm expecting to see logged by the backend.
import { Injectable } from '#angular/core';
import * as io from 'socket.io-client';
#Injectable()
export class ChatService {
private socket: any;
constructor() {
this.socket = io({ 'path': '/sock' });
this.socket.emit('chat message', 'Hello World from browser!');
}
}
Note: I've had several go's at this with and without the /sock part of the url.
I start both servers. Get no console errors in the browser. But in the angular CLI web pack server I get the following messages.
10% building modules 2/2 modules 0 active[HPM] Proxy created: /sock -> http://localhost:3000
[HPM] Subscribed to http-proxy events: [ 'error', 'close' ]
[HPM] GET /sockjs-node/530/z1z3teld/websocket -> http://localhost:3000
[HPM] Upgrading to WebSocket
[HPM] Error occurred while trying to proxy request /sockjs-node/530/z1z3teld/websocket from localhost:4200 to http://localhost:3000 (ECONNRESET) (https://nodejs.org/api/errors.html#errors_common_system_errors)
Are web sockets supported or have I made a silly mistake?
Thanks
I managed to figure it out with a bit of trial and error. I looked at the console for the basic index.html page that works within the backend project. This backend project is basically the chat server demo application on the socket.io website. I noticed that when it opens up the web socket the url looks like the following:
http://localhost:3000/socket.io/EIO=3&transport=websocket&sid=wTvdQTclHXJSUmAmAAAA
So back in the angular CLI project I modified my proxy config to include the /socket.io/ part plus also added a wildcard.
{
"/sock/*": {
"target": "http://localhost:3000/socket.io/",
"ws": true,
"logLevel": "debug"
}
}
Bingo! Now when the service is constructed it opens the socket and emits a message which I can see logged in the backend.

Resources