I'm using create-react-app for my React project (ejected), and I've configured a proxy in package.json. But I don't want to have my credentials committed in this file. So I've added to npm using npm config set my_user xxxx.
I can see them in my ~/.npmrc, too.
"proxy": {
"/api/v3/": {
"target": "https://ourstagingserver.nl/",
"changeOrigin": true,
"ssl": false,
"secure": false,
"headers": {
"username": "$npm_config_my_user",
"password": "$npm_config_my_pass"
}
},
This doesn't work. The username and password are not used in the proxy requests.
But if I add this to "scripts":
"hello": "echo $npm_config_my_user $npm_config_my_pass
and run npm run hello, both are echoed...
Any ideas? Is this supposed to work or am I doing it wrong?
Thx! Gijs
I didn't figure out the use of $npm_config_ variables for this purpose but I did solve the issue of using ENV variables for the proxy in create-react-app:
In scripts/start.js (line 62, below const proxySetting = require(paths.appPackageJson).proxy), add this:
proxySetting[Object.keys(proxySetting)[0]].headers.username = process.env.PROXY_USERNAME;
proxySetting[Object.keys(proxySetting)[0]].headers.password = process.env.PROXY_PASSWORD;
or you could loop over the objects in proxySetting and set the credentials for every object in there if you have multiple API's to proxy to:
Object.keys(proxySetting).forEach(function(proxy) {
proxySetting[proxy].headers.username = process.env.PROXY_USERNAME;
proxySetting[proxy].headers.password = process.env.PROXY_PASSWORD;
});
Note: scripts/start.js is a file that's generated by create-react-app
Related
I am making web scraping site,
and I want get Tags in URL , but they are dynamic sources.
so I can't touch only Cheerio.
people recommended Puppeteer. and my problem was starting
first. I could see Module not found:
Error: Can't resolve 'https' in '/Users/Documents/myMac/Study/bookMarks/node_modules/puppeteer-core/lib/cjs/puppeteer/node'
and also they couldn't find out os, path .....
so I add (I use yarn) webpack and cli
second. I set the webpack.config.js for fallback
resolve:{
fallback:{
"fs":false,
"os": require.resolve("os-browserify/browser"),
"path": require.resolve("path-browserify"),
"https": require.resolve("https-browserify"),
"stream": false,
"zlib": false ,
"crypto": false,
"constants": false,
}
}
because the Err-Message said
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "https": require.resolve("https-browserify") }'
- install 'https-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "https": false }
but the err messages still there when I yarn start
Third. I thought if the config didn't set .
so I did ' $ webpack --config webpack.config.js'
I couldn't see the err
but still when I did yarn start, problem are there
4th. I add fs, os, http..... (in the err's module name) using yarn
I can see the dependencies
"os": "^0.1.2", "path": "^0.12.7",
and added
"browser": {
"crypto": false,
"fs": false,
"path": false,
"os": false,
"net": false,
"stream": false,
"tls": false
}
setting in package.json
but,,
.
.
.
ERROR in ./node_modules/puppeteer-core/lib/cjs/puppeteer/node/FirefoxLauncher.js 43:29-42
Module not found: Error: Can't resolve 'fs' in '/Users/Documents/myMac/Study/bookMarks/node_modules/puppeteer-core/lib/cjs/puppeteer/node'
ERROR in ./node_modules/puppeteer-core/lib/cjs/puppeteer/node/ProductLauncher.js 65:13-26
Module not found: Error: Can't resolve 'fs' in '/Users/Documents/myMac/Study/bookMarks/node_modules/puppeteer-core/lib/cjs/puppeteer/node'
webpack compiled with 41 errors
I am having 41 errors
5th . I removed folder the node_modules and yarn.lock
and did
$ yarn cache clean $ yarn install
it doesn't work
also I removed puppeteer-core and re-add
and i have 41 errors still
do you have another way
or
can I alternate puppeteer?
at last
this is js module using puppeteer
const puppeteer = require('puppeteer-core');
const DomParser = require('dom-parser');
async function getTagList(url) {
const tagListText = new Array();
try{
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto(url);
const html = await page.content();
const parser = new DomParser();
const dom = parser.parseFromString(html);
const tagList = dom.getElementsByClassName('tag_area')[0].getElementsByTagName('a');
tagListText = Array.from(tagList).map(tag => tag.textContent);
await browser.close();
}catch(error) {
console.error(error);
}
return tagListText;
}
module.exports = { getTagList };
and I am using chatGPT. he recommended setting in webpack.config.js
Specially fallback -> fallbacks
and it can't terminal said fallbacks isn't option
I use webpack5
So I have Create React App with typescript template. I have also integrated sonarqube with it.
First When I ran sonar report with below configuration,
scanner(
{
serverUrl: "http://localhost:9000",
token: "*****",
options: {
...
"sonar.tests": "./src",
"sonar.test.inclusions": "**/*.test.tsx,**/*.test.ts, **/*.js",
"sonar.typescript.lcov.reportPaths": "coverage/lcov.info",
"sonar.testExecutionReportPaths": "test-report.xml"
},
},
() => process.exit()
);
The result is as below,
as you can see, it includes following file which is fine.
Now I am changing sonar-scanner.js configuration as below,
const testExclusions = `./src/index.ts,./src/reportWebVitals.ts, ./src/core/constants/**/*,./src/core/interfaces/**/*`;
scanner(
{
serverUrl: "http://localhost:9000",
token: "*****",
options: {
...
"sonar.tests": "./src",
"sonar.test.inclusions": "**/*.test.tsx,**/*.test.ts, **/*.js",
"sonar.test.exclusions": `${testExclusions}` <<=== I don't know if this line plays any role.
"sonar.typescript.lcov.reportPaths": "coverage/lcov.info",
"sonar.testExecutionReportPaths": "test-report.xml"
},
},
() => process.exit()
);
BUT again result is same. there is no change in the report.
Then, I introduced jest configuration in package.json as follow,
"test:report": "npm run test -- --watchAll=false --coverage --testResultsProcessor jest-sonar-reporter",
...
...
"jest": {
"collectCoverageFrom": [
"src/**/*.{js,jsx,tsx,ts}",
"!src/**/*.d.ts",
"!src/reportWebVitals.ts",
"!src/index.ts",
"!src/core/constants/**/*",
"!src/core/interfaces/**/*"
]
}
and I ran npm run test:report and it generated new test-report.xml with below files,
as you can see, it doesn't cover excluded files/directories.
When I ran sonar-scanner again, I believed now it will not show excluded files/directories in sonar coverage report but it is not the case yet. It is still including those files and directories.
What is wrong with this setup ?
x
Make changes as follow,
1) For some reason, need to remove ./ before src as below,
const testExclusions = `src/index.ts,src/reportWebVitals.ts, src/core/constants/**/*,src/core/interfaces/**/*`
2) use: sonar.coverage.exclusions property in sonar options instead of sonar.test.exclusions
"sonar.coverage.exclusions": `${testExclusions}`
Optional:
3) if you want to remove jest configuration from package.json. It is fine.
Hello I am doing blockchain with React but when I import Web 3 using
import Web3 from 'web3'
it give me this error:
./node_modules/web3-eth-accounts/lib/index.js
Module parse failed: Unexpected token (225:12)
You may need an appropriate loader to handle this file type.
| }
| return signed({
| ...tx,
| chainId: args[0],
I am using node 14.17.1 and I created this using
create-react-app my-app --scripts-version 1.1.5
and I installed web3 using
npm install web3
This is the tsconfig.json file and this file showing errors as well
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"outDir": "./lib",
"esModuleInterop": true
},
"include": [
"./src"
]
}
and index.js code where the error is referring
return signed({
...tx,
chainId: args[0],
nonce: args[1],
networkId: args[2],
...args[3] // Will either be gasPrice or maxFeePerGas and maxPriorityFeePerGas
});
Your project's created with --scripts-version 1.1.5 which mean its babel can not parse ..., consider to use higher scripts-version. For me, I upgraded from 1.1.4 to 3.2.0
I am trying to set up Storybook in a project. My project is runing on react#^16, and I'm using typescript, with a custom babel and webpack setup for development and build. To set up storybook, I did
npx sb init
This installs everything needed. It puts a .storybook folder in the root folder, and a stories folder in my src folder with some prefab components and stories in tsx format (which is what I want):
The .storybook/main.js file seems fine:
module.exports = {
"stories": [
"../src/**/*.stories.mdx",
"../src/**/*.stories.#(js|jsx|ts|tsx)"
],
"addons": [
"#storybook/addon-links",
"#storybook/addon-essentials"
]
}
And the average .stories.js file automatically installed by npx sb init also seems fine:
import React from 'react';
// also exported from '#storybook/react' if you can deal with breaking changes in 6.1
import { Story, Meta } from '#storybook/react/types-6-0';
import { Header, HeaderProps } from './Header';
export default {
title: 'Example/Header',
component: Header,
} as Meta;
const Template: Story<HeaderProps> = (args) => <Header {...args} />;
export const LoggedIn = Template.bind({});
LoggedIn.args = {
user: {},
};
export const LoggedOut = Template.bind({});
LoggedOut.args = {};
But when I run npm run storybook, the storybook landing page has no stories. Even though it had installed some default stories to start playing with. It says:
Oh no! Your Storybook is empty. Possible reasons why:
The glob specified in main.js isn't correct.
No stories are defined in your story files.
As requested, here is a link to the repo so you can dig a bit deeper into the structure, weback config, etc. Note I have not committed the npx sb init changes yet, so you won't see the files there, only my starting point just before running the sb init.
I haven't had any issues getting npx sb init to work with a standard create-react-app, but with my custom webpack build and typescript, its just empty. What's going wrong?
Edit: Additional detail
I realize that just running npx sb init, then npm run storybook throws this error:
ERROR in ./.storybook/preview.js-generated-config-entry.js
Module not found: Error: Can't resolve 'core-js/modules/es.array.filter'
Based on this thread, installing core-js#3 solves the problem and storybook runs, though with no stories.
It seems like the babel plugin transform-es2015-modules-amd doesn't fit right with storybook since sb still uses your babel configuration.
You might need to remove it then it would work:
{
"plugins": [
// "transform-es2015-modules-amd", // Remove this plugin
]
}
If you want to have a special babel configuration for storybook, place it .storybook/.babelrc so the configuration would be simple like this:
.storybook/.babelrc:
{
"presets": ["#babel/preset-env", "#babel/preset-react", "#babel/preset-typescript"]
}
NOTE: You might miss to forget install #babel/preset-typescript to help you transform your typescript code.
Maybe you have problems with the stories path, try to save only "../src/**/*.stories.js" in your config to see if its the reason
"stories": [
"../src/**/*.stories.mdx",
"../src/**/*.stories.#(js|jsx|ts|tsx)"
]
In case of dealing with arcgis-js-api in sb, you have to declare #arcgis/webpack-plugin in storybook's webpack configuration by adding to its config.
Here are a few steps you have to do:
Add webpackFinal property in .storybook/main.js with following content:
const ArcGISPlugin = require('#arcgis/webpack-plugin');
module.exports = {
// ...
webpackFinal: (config) => {
// Add your plugin
config.plugins.push(
new ArcGISPlugin(),
);
// Since this package has used some node's API so you might have to stop using it as client side
config.node = {
...config.node,
process: false,
fs: "empty"
};
return config;
}
};
One more thing to be aware of, some components are importing scss files, so you might need to support it by adding a scss addon '#storybook/preset-scss'
// Install
npm i -D #storybook/preset-scss css-loader sass-loader style-loader
// Add to your current addons
{
addons: ['#storybook/addon-links', '#storybook/addon-essentials', '#storybook/preset-scss'],
}
Like a tmhao2005 say. Storybook still uses your babel configuration. And this is the intended behavior. This thread at github also describes how the fix similar issue.
Updated your config .storybook/main.js.
If you use .babelrc:
babel: async options => ({ ...options, babelrc: false })
Or .babel.config.js:
babel: async options => ({ ...options, configFile: false })
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.