React App Not Loading When Using http-proxy-middleware - javascript

Alright, I've about reached the end of my sanity on this one.
So, I have a basic React frontend w/ an Express backend. React is running off of localhost:3000, the backend is running off of localhost:3030. Following along on a guide for setting up some Spotify integration, everything works fine up until I hit the portion on setting up a proxy. (I have a slightly different setup from the Spotify guide, all my stuff runs through /spotify/auth rather than /auth)
I installed http-proxy-middleware, created the setupProxy.js in my /src folder, and if I ever try to load up localhost:3000 as normal, I get nothing-- my app doesn't load at all.
The only way to have the app appear again is to remove the file. The one on the spotify guide is a bit out of date as far as I can tell anyway, but even using suggestions found elsewhere, I've gotten no luck. Here is the current setup I have for my setupProxy.js file:
const { createProxyMiddleware } = require("http-proxy-middleware");
module.exports = function (app) {
app.use(
"/spotify/**",
createProxyMiddleware({
target: "http://localhost:3030",
changeOrigin: true,
})
);
};
I've even removed the actual fetch that would be making use of the proxy and still have no luck loading my page. I am also unable to use "proxy": "http://localhost:3030" in my package.json as it throws:
Invalid options object. Dev Server has been initialized using an options object that does not match the API schema.
- options.allowedHosts[0] should be a non-empty string."

Managed to solve my problem, though I am still unsure of why it works.
The issue I was running into stems from using "type": "module" in the package.json. I was using correct import statements in all of my backend, as well as tried to use it for the setupProxy.js as well, however this would always result in the issue from the question. After removing the line and swapping out the imports for requires in my backend, everything started working.
It seems like a strange compatibility issue, but there's probably a much better explanation.

Had the same problem as you where my react app wasn't loading because of http-proxy-middleware. Different problem/solution, but for people that also had this problem, and were following this youtube video https://www.youtube.com/watch?v=hxyp_LkKDdk
The tutorial has
const proxy = require("http-proxy-middleware")
instead of
const {createProxyMiddleware} = require("http-proxy-middleware")
After I made that change, my issue was solved. Don't forget to change "proxy" to "createProxyMiddleware" in app.use() as well

Related

Failed to resolve module specifier

I`m only starting my JS journey and I will be really grateful if you help me to receive data using the JS. I found that info on the alcor exchange site that is the exchange site for wax (gaming crypto currency).
What is on site:
// Code not tested yet, and provided for explanation reason
import fetch from 'node-fetch'
import { Api, JsonRpc, RpcError } from 'eosjs'
const rpc = new JsonRpc('https://wax.greymass.com', { fetch })
// Get buy orderbook from table
const { rows } = await rpc.get_table_rows({
code: 'alcordexmain',
table: 'buyorder',
limit: 1000,
scope: 29, // Market id from /api/markets
key_type: 'i128', // we are using it for getting order sorted by price.
index_position: 2
})
I faced with some trouble because of JSHint version and updated it to 9. But still "await" is red and JSHint is asking for semicolon after it - which causes huge amount of new errors. However the project is opening in the browser with no info of course. But in the console I see an error.
index.html:1 Uncaught TypeError: Failed to resolve module specifier "node-fetch". Relative references must start with either "/", "./", or "../".
P.S. I checked the posts with such error but actually didn't understand what should I do because all of them are proposing some changes for JSON file and I only have index.html and that js. file.
There is a difference between JavaScript in your browser and JavaScript on a server.
JavaScript in a browser is the code that can be injected into HTML (inlined or linked), which is evaluated by the browser.
JavaScript on a server is not related to JavaScript in a browser. The language is the same, but the environment is not. It's like “draw in Paint” and “draw on a real life canvas”. Colors are the same, but everything else is not.
So, what you are trying to do here is to run server-side JavaScript in a browser. That's the real reason you're getting this error.
There are two ways to fix this error.
Probably the one you should go
You should install Node.js, read about npm, init your npm project, put everything into .js file and eval using Node.
In a nutshell, let's say you've already installed Node.js and node -v outputs something in your terminal. Then everything you need to do is:
$ cd path/to/the/directory/you/like
$ npm init -f
$ npm install --save node-fetch eosjs
$ touch index.js
Then edit index.js using your favorite editor, adding there the code you're trying to run.
You may encounter error due to using await on a “top-level”. In this case, put it into an async function:
import fetch from 'node-fetch'
import { Api, JsonRpc, RpcError } from 'eosjs'
const rpc = new JsonRpc('https://wax.greymass.com', { fetch })
(async () => {
const { rows } = await rpc.get_table_rows({
code: 'alcordexmain',
table: 'buyorder',
limit: 1000,
scope: 29, // Market id from /api/markets
key_type: 'i128', // we are using it for getting order sorted by price.
index_position: 2
});
})();
Aaaand, that's it. You do not need to run browser here at all.
Probably the one you should not go, but can
If you need to run your JavaScript in a browser, then you need to either bundle all the deps using a tool like webpack (which still requires you to use Node.js & npm), or you may replace the deps you're trying to use with client-side alternatives.
E.g. instead of requiring node-fetch you may use Fetch API.
What to use instead of eosjs I do not know, but if you decide to use this dependency in a browser, you will at least need to use import maps to tell the browser how to resolve such dependencies. Because, well, the error you've got tells you exactly this: your browser does not know what you're trying to import. Browsers use URLs as import paths, not ids (or “bare names”).

What is the purpose of #next/react-dev-overlay?

I am working on a NextJs project. In it, I have found this piece of code inside next.config.js:
const withTM = require('next-transpile-modules')([
'some package',
'some package',
'emittery',
'#next/react-dev-overlay'
]);
I was wondering what is the purpose of this #next/react-dev-overlay and was not able to find anything online. The only thing was this unanswered question in the nextjs github issues. When I remove it, it seems that the project is working as expected. My question is what is the purpose of this #next/react-dev-overlay package and should I remove it?
The #next/react-dev-overlay package is a development-only overlay for React apps. It's used internally by Next.js to display the error messages you see in development.
This is what the error overlay looks like when a client-side error occurs in a Next.js app:
As to why that package was included in next.config.js, I can only guess that it's being used directly in that app, and needs to be transpiled to be used. Most of the times you wouldn't need to install it or use it directly.

Nuxt module that adds another website as serverMiddleware

The idea
First you have a main Nuxt website like any other. Then you add my module to your project. My module then adds a subdomain "admin.example.com" to your project which is a fully fleshed out Nuxt based website all of its own but running from your projects process, so instead of making two website projects that have to be started separately the idea is that I can make my one website project and then one module project which adds the other website, turning three projects into two.
Code
module.js
this.addServerMiddleware(vhost('admin.website.com', adminApp));
adminApp.js
const {Nuxt, Builder} = require('nuxt');
const config = require('../admin/nuxt.config');
config.dev = true;
const nuxt = new Nuxt(config);
if (nuxt.options.dev) {
new Builder(nuxt).build()
.catch(function(error) {
console.log(error);
})
}
module.exports = nuxt.render;
Part of nuxt.config.js from the admin website
// __dirname leads to my modules directory
// process.cwd() leads to the main websites folder
module.exports = {
mode: 'universal',
srcDir: __dirname,
rootDir: __dirname,
modulesDir: process.cwd(),
The problem
Whenever I go to "admin.website.com" it results in the following message:
I've tried tonnes various changes and tweaks already but nothing seems to be working. As far as I can tell it might have to do with the fact that either A) the website gets built somewhere it doesn't find the generated resource files, or B) that I haven't prayed enough to the spaghetti monster.
I've tried exporting adminApp as an Express app that uses app.use(nuxt.render) but that results in the same error so I'm certain that's not the issue. I've tried using an Express app for api.website.com and that works just fine, so I know I'm like THIS |--| close to making this all work. Adding subdomains like this does work and each subdomain can be an Express app, but for some reason Nuxt can't find any resources when used this way. According to https://nuxtjs.org/api/nuxt-render/ nuxt.render(req, res) as you can see takes req and res as arguments, which should mean I don't need to use it via an Express app, serverMiddleware is already an Express app.
Thoughts?
I ran in this error before when serving apps through serverless. I think that you need to explicitly set a publicPath or a buildDir in nuxt.config.js for both apps to make setup work. Your problem could be that all the build assets are generated in the same folder, causing one of the apps to not find the build assets. The buildDir property is set on the nuxt.config.js and the publicPath setting is defined on the build property.
More info here:
https://nuxtjs.org/api/configuration-builddir
https://nuxtjs.org/api/configuration-build#publicpath

Webpack error, Loading chunk failed

Stack: Webpack 4.16.0, Node8, Vuejs2
I am seeing the below error, whilst serving my Vuejs application.
Error: Loading chunk 4 failed.
(missing: https://myapp.com/ui.chunk.bundle.js)
at HTMLScriptElement.s (demo:1)
This error is consistent across builds, the actual file itself is accesible via the URL.
I am using code splitting via import() and the initial app loads fine, but then the flow will break when another chunk is loaded, it can also vary between ui.chunk.bundle.js & vendors~ui.chunk.bundle.js.
When building for production, a new error is shown, but it seems related as also linked to loading modules:
demo:1 TypeError: Cannot read property 'call' of undefined
at o (demo:1)
at Object.349 (ui.chunk.bundle.js:1)
at o (demo:1)
at o.t (demo:1)
I have tried upgrading webpack and babel, but am at a loss as to what this could be down to as it was working perfectly fine before.
When running the application on my local machine and not Google App Engine, everything seems fine.
How the app is loaded:
It is loaded into other website via a script tag, so domainA.com runs the script tag which calls myapp.com/js and the flow begins, i.e the app loads various chunks based on some logic.
When accessing the webpack generated index page bundle at myapp.com everything loads correctly.
Please help!
That is rather deep and surely not easily fixed in two steps, best you create a new project using cli, if convenient with recommended presets, and if it still persist check the npm packages you installed and make sure none of them are discontinued and are up-to-date at least according to your version of vue.
Its might be due to "webpack.config.js" where you can just try with updating output object
module.exports = {
output: {
chunkFilename: '[id].chunk.[chunkhash].js',
}
};
Hope it should work!
This might be a cross site scripting problem.
Make sure that myapp.com sets the correct headers.
On myapp.com, set this header:
Access-Control-Allow-Origin: https://domainA.com
You should also make sure, that your script tag has async set to false:
<script async="false" …

I need a strongloop example wrote in javascript without angular

I want to have a strongloop example only using javascript without angular.
There's no complete working example without angular for now.
I want to simply include the browser.bundle.js in my index.html, then sync data from/to server side. In fact, I'm trying to replace pouchdb in my program since the couchdb seems not success in open source community.
I can't follow up this document correctly:
Running Loopback in the browser
create browser-app.js with the content from Running Loopback in the browser
copy past the content to browser-app.js
npm install loopback loopback-boot
browserify browser-app.js -o app.bundle.js Then I got error: Error: Cannot find module 'loopback-boot#instructions' from '/Users/simba/Projects/traveller-app/client/node_modules/loopback-boot'
There are few steps for this but its pretty simple.
Bootstrap your application via slc loopback.
Delete server/boot/root.js.
Uncomment two lines in server/server.js, it should look like:
...
// -- Mount static files here--
// All static middleware should be registered at the end, as all requests
// passing the static middleware are hitting the file system
// Example:
var path = require('path'); //this line is now uncommented
app.use(loopback.static(path.resolve(__dirname, '../client'))); //this line is now uncommented
...
Create index.html in the client dir (ie. client/index.html) with your contents.
That should get you a basic set up with just a basic front-end working. Let me know if you have any more issues.

Categories