It is my first project in that I'm using electron, I'm dealing with a few problems creating standalone publish from the project.
Here's my electron main.js file:
const path = require("path");
const electron = require("electron");
const isDev = require("electron-is-dev");
// Module to control application life.
const app = electron.app;
// Module to create native browser window.
const BrowserWindow = electron.BrowserWindow;
const url = require("url");
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow;
function createWindow() {
// Create the browser window.
mainWindow = new BrowserWindow({ show: false });
// cm: open app in fullscreen mode
mainWindow.maximize();
mainWindow.show();
// cm: remove default menu bar
mainWindow.setMenuBarVisibility(false);
if (isDev) {
mainWindow.loadURL(
"http://localhost:3000"
);
} else {
mainWindow.loadFile("./dist/index.js");
}
// Open the DevTools.
mainWindow.webContents.openDevTools();
// Emitted when the window is closed.
mainWindow.on("closed", function () {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
mainWindow = null;
});
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on("ready", createWindow);
// Quit when all windows are closed.
app.on("window-all-closed", function () {
// On OS X it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== "darwin") {
app.quit();
}
});
app.on("activate", function () {
// On OS X it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (mainWindow === null) {
createWindow();
}
});
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
And my package.json scripts are:
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"electron": "electron .",
"package-win": "electron-packager . IranFMCG --overwrite --platform=win32 --arch=ia32 --icon=assets/icons/win/icon.ico --prune=true --out=release-builds --version-string.CompanyName=CE --version-string.FileDescription=CE --version-string.ProductName=\"IranFMCG\"",
},
Everything is fine when the react application is running and I'm using "npm run electron" but after running "npm run package-win" and after that when I'm running exe file I am facing errors.
I think that is because I'm not running react app anymore, but I want to use react build files is it possible?
I have developed .NET5 web api and React app in two different projects.
Now it's time to deploy API and React app to IIS, but on trying to achieve that I realized that they have to be added as same app in IIS.
I wish that routing setup would be:
/ => React App
/api/v1/controller/method => API endpoints
Both of my apps individually has this setup, I just cannot merge them :/
I cannot find examples where dotnet template isn't used. So far I have tried to accomplish that through this code (I have skipped non related configurations code):
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp";
});
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSpaStaticFiles();
I have managed to solve it by adding these lines:
in ConfigureServices
if (HostingEnvironment.IsProduction())
{
services.AddSpaStaticFiles(configuration =>
configuration.RootPath ="ClientApp");
}
in Configure
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
if (env.IsProduction())
{
app.UseSpaStaticFiles();
app.UseSpa(spa =>
{
spa.Options.DefaultPage = "/index.html";
});
I have achieved in .NET 6 this by:
1 - Copying the production build of my React app to the Web API wwwroot folder, using a postbuild step in package.json
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"postbuild": "move build ../YourWebAPIProject/wwwroot",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
2 - Updated the program.cs in the Web API project to contain the following
app.UseRouting();
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(config =>
{
config.MapControllers();
config.MapFallbackToController("Index", "Fallback");
});
3 - Add a fallback controller to handle the react routes
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace YourNameSpace
{
[AllowAnonymous]
public class FallbackController : Controller
{
public IActionResult Index()
{
return PhysicalFile(
Path.Combine(
Directory.GetCurrentDirectory(), "wwwroot", "index.html"),
"text/HTML");
}
}
}
This approach allows both WebAPI and React routes to work, served from the WebAPI project.
Hope this is useful to someone
js and react newbie...playing around with testing frameworks...here's the code:
import React from 'react';
// import CheckboxWithLabel from '../CheckboxWithLabel';
import {shallow} from 'enzyme'; //not installed...
//var x = require ('../CheckboxWithLabel.js');
test('CheckboxWithLabel changes the text after click', () => {
const checkbox = shallow(
<CheckboxWithLabel labelOn="On" labelOff="Off" />
);
expect(checkbox.text()).toEqual('Off');
checkbox.find('input').simulate('change');
expect(checkbox.text()).toEqual('On');
});
The react-scripts test error is:
Cannot find module 'enzyme' from 'checkboxWithLabel-test.js'
While the jest error is:
Jest encountered an unexpected token
SyntaxError: /Users/shriamin/Development/js_prj_react_django_etc/jest_react_demo/my-app/src/__tests__/checkboxWithLabel-test.js: Unexpected token (12:4)
10 | test('CheckboxWithLabel changes the text after click', () => {
11 | const checkbox = shallow(
> 12 | <CheckboxWithLabel labelOn="On" labelOff="Off" />
| ^
13 | );
14 | expect(checkbox.text()).toEqual('Off');
15 | checkbox.find('input').simulate('change');
i have no idea why jest would throw this error...react-scripts test makes sense to me since enzyme is not installed....please tell me does jest suck or am i doing something wrong configuring jest (installed via npm and update package.json).
NOTE: i don't have babel installed...i don't know what that is yet.
thanks
You arrived at the answer yourself. To use jest your tests need to go through babel for the runner to understand react syntax. take a look at the babel-doc to understand it at greater detail. it's just a transformation tool that transforms fancy syntax into something javascript understands. install the following plugins and presets.
Presets
npm i --save #babel/preset-env
npm i --save #babel/preset-react
Plugins
npm install --save babel-plugin-transform-export-extensions
in your .babelrc add the following lines:
{
"env": {
"test": {
"presets": [
"#babel/preset-env",
"#babel/preset-react"
],
"plugins": [
"transform-export-extensions",
],
"only": [
"./**/*.js",
"node_modules/jest-runtime"
]
}
}
}
Now try running jest on the command-line from your project directory to make sure your tests are configured correctly.
react-scripts is a preconfigured set of commands that come out of the box with create-react-app if you want to use that instead of jest command, check here.
react-scripts expects your tests folder location to follow a certain convention.
this is probably why the tests weren't getting fetched when the react-scripts test command was run out of the box.
in package.json change
"scripts": {
"test": "jest",
},
to the following:
"scripts": {
"test": "react-scripts test",
},
i.e. don't change to jest in the first place
The error described here seem to be jsx that isn't interpreted, isn't your test file extension js instead of jsx ?
I would like to have proxy in my react client, my package.json contains:
...
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"proxy": {
"/auth/google": {
"target": "http://localhost:5000"
}
},
...
But when I ran it, I got error
When specified, "proxy" in package.json must be a string.
[1] Instead, the type of "proxy" was "object".
[1] Either remove "proxy" from package.json, or make it a string.
I tried to convert to string, no errors but proxy is not working
"proxy": "http://localhost:5000"
My App.js
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>hey there</p>
Sign In With Google
</header>
</div>
The issue that you are facing is because of CRA v2.
Firstly, you will not require any additional configuration if you are just using a plain string in your proxy. But the moment you use an object, you are using advanced configuration.
So, you would have to follow the steps listed below:
Install http-proxy-middleware by typing npm i --save http-proxy-middleware
Remove the entries from package.json:
"proxy": {
"/auth/google": {
"target": "http://localhost:5000"
}
}
Now create a setup file for your proxy. You should name it setupProxy.js in your src folder on the client side and type the following code:
const proxy = require('http-proxy-middleware');
module.exports = function(app) {
app.use(proxy('/auth/google',
{ target: 'http://localhost:5000/' }
));
}
for more info check this
I think it is "create-react-app" issue.
You can go to https://github.com/facebook/create-react-app/issues/5103
to migration to the new proxy handling method.
For short, you just need to install a new library called "http-proxy-middleware"
npm install http-proxy-middleware --save
And then create a new file "src/setupProxy.js", and type
const proxy = require('http-proxy-middleware');
module.exports = function(app) {
app.use(proxy('/auth/google', { target: 'http://localhost:5000/' }));
};
Hope this can solve your problem, happy hacking!
First, install http-proxy-middleware using npm or Yarn:
$ npm install http-proxy-middleware --save
$ # or
$ yarn add http-proxy-middleware
Next, create src/setupProxy.js and place the following contents in it:
const proxy = require('http-proxy-middleware')
module.exports = function(app) {
// ...
}
Now, migrate each entry in your proxy object one by one, e.g.:
"proxy": {
"/api": {
"target": "http://localhost:5000/"
},
"/*.svg": {
"target": "http://localhost:5000/"
}
}
Place entries into src/setupProxy.js like so:
const proxy = require('http-proxy-middleware')
module.exports = function(app) {
app.use(proxy('/api', { target: 'http://localhost:5000/' }))
app.use(proxy('/*.svg', { target: 'http://localhost:5000/' }))
}
You can also use completely custom logic there now!
I have got this working response from this link and hence sharing-https://github.com/facebook/create-react-app/issues/5103
For people in 2020,
Install http-proxy-middleware by typing npm i --save http-proxy-middleware inside the client folder.
Remove the entries from package.json:
"proxy": {
"/auth/google": {
"target": "http://localhost:5000"
}
}
Now create a setup file for your proxy. You should name it setupProxy.js in your src folder on the client side and type the following code:
const { createProxyMiddleware } = require("http-proxy-middleware");
module.exports = function (app) {
app.use(
createProxyMiddleware("/auth/google", { target: "http://localhost:5000/" })
);
};
PS: You don't need to include setupProxy.js anywhere in server.js or index.js. just copy and paste.
The following worked for me:
Remove "proxy" from your package.json.
Install 'http-proxy-middleware' in the client directory. To do this, cd into the client directory and run "npm i --save http-proxy-middleware". Then, create a new file in the src directory of your client called "setupProxy.js". Place the following code in this file:
const { createProxyMiddleware } = require('http-proxy-middleware');
const proxy = require('http-proxy-middleware');
module.exports = function(app) {
app.use(createProxyMiddleware('/api/', // replace with your endpoint
{ target: 'http://localhost:8000' } // replace with your target
));
}
restart the server, and you should be good to go.
Change the proxy to something like this and hope it will work as it worked for me.
"proxy": "http://localhost:5000/auth/google"
At this moment i'm using React 16.8.13 this works fine:
1- delete "proxy": {***} from package.json file
2- type npm install http-proxy-middleware
3- create the file src/setupProxy.js
4-insert the code as following:
const {createProxyMiddleware} = require('http-proxy-middleware');
module.exports = (app) => {
app.use(
createProxyMiddleware('/endpoint/*', {
target: 'http://address/',
secure: false,
}),
);
};
If you need to proxy requests and rewrite urls, for example localhost:3000/api/backend/some/method to https://api-server.example.com/some/method, you need to use pathRewrite option also:
const {createProxyMiddleware} = require("http-proxy-middleware");
module.exports = function(app) {
app.use(
"/api/backend",
createProxyMiddleware({
target: "https://api-server.example.com",
changeOrigin: true,
pathRewrite: {
"^/api/backend": "",
},
})
);
};
install "http-proxy-middleware" into your client, "not inside server".
Add setupProxy.js inside of your client/src/ directory.
(should be like this: client/src/setupProxy.js)
Add the below lines to it.
const proxy = require("http-proxy-middleware");
module.exports = app => {
app.use(proxy("/auth/google", { target: "http://localhost:5000/" }));
};
That's it, get inside of your google dev console and add localhost:3000/auth/google/callback to your project.
https://github.com/facebook/create-react-app/issues/5103
Move advanced proxy configuration to src/setupProxy.js
This change is only required for individuals who used the advanced proxy configuration in v1.
To check if action is required, look for the proxy key in package.json. Then, follow the table below.
I couldn't find a proxy key in package.json
No action is required!
The value of proxy is a string (e.g. http://localhost:5000)
No action is required!
The value of proxy is an object
Follow the migration instructions below.
If your proxy is an object, that means you are using the advanced proxy configuration.
Again, if your proxy field is a string, e.g. http://localhost:5000, you do not need to do anything. This feature is still supported and has the same behavior.
First, install http-proxy-middleware using npm or Yarn:
$ npm install http-proxy-middleware --save
$ # or
$ yarn add http-proxy-middleware
Next, create src/setupProxy.js and place the following contents in it:
const proxy = require('http-proxy-middleware')
module.exports = function(app) {
// ...
}
Now, migrate each entry in your proxy object one by one, e.g.:
"proxy": {
"/api": {
"target": "http://localhost:5000/"
},
"/*.svg": {
"target": "http://localhost:5000/"
}
}
Place entries into src/setupProxy.js like so:
const proxy = require('http-proxy-middleware')
module.exports = function(app) {
app.use(proxy('/api', { target: 'http://localhost:5000/' }))
app.use(proxy('/*.svg', { target: 'http://localhost:5000/' }))
}
You can also use completely custom logic there now! This wasn't possible before.
It's worked.
app.use(
'/api',
proxy({ target: 'http://www.example.org', changeOrigin: true })
);
changeOrigin:true
In my cases i didn't need src/setupProxy.js...
I do that with axios... Check About Axios Proxy
Check in node library if you have it or not: http-proxy-middleware is optional i didn't need it!!!
Just try to restart server side, and that's it!!!
Add to check:
componentDidMount(){
axios.get('/api/path-you-want').then(response=>{
console.log(response)
})
}
This is related to a bug in create-react-app version2.
Just run
$ npm install react-scripts#next --save
$ # or
$ yarn add react-scripts#next
Answer found at:
https://github.com/facebook/create-react-app/issues/5103
...
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"proxy": {
"/auth/google": {
"target": "http://localhost:5000"
}
},
...
When specified, "proxy" in package.json must be a string.
Just change `"proxy": "http://localhost:5000"` and you are good to go.
If that doesn't solve the problem then register your proxy using **http-proxy-middleware**
$ npm install http-proxy-middleware --save
$ # or
$ yarn add http-proxy-middleware
Then create setypProxy.js file under src directory the put the following code.
const proxy = require('http-proxy-middleware');
module.exports = app => {
app.use(
proxy('/auth/google', {
target: 'http://localhost:5000'
})
);
app.use(
proxy('/auth/facebook', {
target: 'http://localhost:6000'
})
);
};
Create a setupProxy.js file inside the src folder and copy-paste the below code.
const { createProxyMiddleware } = require("http-proxy-middleware");
module.exports = function (app) {
app.use(
createProxyMiddleware("/auth/google", {
target: "http://localhost:5000/",
})
);
};
This worked for me (just as several people have already replied). But I write this just in case someone asks whether this is still a valid answer in 2021.
Delete this from your package.json file:
"proxy": {
"/auth/google": {
"target": "http://localhost:5000"
}
Install proxy middleware by running npm install --save http-proxy-middleware.
Create setupProxy.js file in your src (right next to the index.js file) file on the frontend.
In that setupProxy.js file put:
const proxy = require('http-proxy-middleware');
module.exports = function(app) {
app.use(proxy('/auth/google',
{ target: 'http://localhost:5000/' }
));
Of course, your port can be anything. It does not have to be 5000. Where ever you are running your backend service at.
That is it. You do not have to import this file anywhere. It works as it is.
After creating a file in the client side (React app ) called
src/setupProxy.js make sure you restart the server. The package.json file needs to restarted since you were dealing with a file outside the source directory.