Can't solve strict-origin-when-cross-origin. React + AdonisJS - reactjs

I have a server, in which I'm running two different applications. The frontend (express + React) is running on 443 port, and the AdonisJS api is running on 3333 port. They share the same domain (something.com, for example), but I need to add the port when calling the api. The problem is, when I try to hit an endpoint from my api from React, I get this error: strict-origin-when-cross-origin. Actually, I'm not sure if this is an error, but I can't make any request at all. From another client, such as Insomnia, the request works like magic.

I fixed the issue by changing the AdonisJS cors config file. I switched the origin value from true to *.

Besides adding the proxy instruction in package.json
"proxy": "http://localhost:5000", I also had to remove the host from the api url request, so:
const apiData = await axios.get('http://127.0.0.1:5000/api/get-user-data');
became
const apiData = await axios.get('/api/get-user-data');
The link provided by #ShawnYap was really helpful https://create-react-app.dev/docs/proxying-api-requests-in-development/

Related

tried to access the data via axios but Response to preflight request doesn't pass access control check

I was working over react and made a request using axios but in the browser it shows "Response to preflight request doesn't pass access control check" i had installed the corx extension but still getting the same error
Assuming you are using create-react-app you can try defining a proxy property in your package.json file and give the url to your api server, something like
"proxy": "http://localhost:8000".
This will proxy your api calls through the express server provided within create-react-app without the need for any CORS configuration in your browser
Note : This can be only used in your local environment and for production setup, you should try alternate approaches by configuring CORS setting in the API server or hosting the UI and API applications under the same hostname

ReactJS backend requests and proxy

I have a couple of questions regarding how ReactJS should work in development and production. My ReactJS application was built starting from creare-react-app boilerplate. I have a SpringBoot backend listening on port 8080. The first thing I noticed is that if I set a code like this to make requests the code hang:
async componentDidMount() {
...
const response = await fetch('http://localhost:8080/api/compliance');
I need to convert it into:
async componentDidMount() {
...
const response = await fetch('/api/compliance');
and then add the line:
"proxy": "http://localhost:8080",
and this works fine. The problem is that when I put this in a pre-production environment (or integration environment) where I have a URL like http://www.mywebsite.com I got:
Invalid Host Header
Looking on the web I noticed that probably this could be to:
1. proxy that checks. the HTTP Header host and verify it to avoid security attacks
2. webpack package
I would like to understand:
1. Is proxy really necessary to let ReactJS app talk with its backend?
2. If no, how I can solve the issue (currently solution on the web didn't solve my problem)?
Generally proxy is not meant for production. Your app should provide both app and api on same port, on one server. https://stackoverflow.com/a/46771744/8522881

How to fix 431 Request Header Fields Too Large in React-Redux app

I'm working through a MERN sign up/login auth tutorial on youtube that uses Redux. When attempting to POST a test user to the server in Postman, I receive the 431 header request is too large error response.
I've read in some places that clearing the cache/history in your browser works, so I've tried that to no avail. I've also added in a "Clear-Site-Data": "*" entry to the header request (in addition to "Content-Type": "application/json") which hasn't worked, either.
Client Side Code for Sign Up
onSubmit = e => {
e.preventDefault();
const { name, email, password } = this.state;
const newUser = {
name,
email,
password
};
this.props.register(newUser);
};
//redux actions
export const register = ({ name, email, password }) => dispatch => {
const config = {
headers: {
"Content-Type": "application/json",
"Clear-Site-Data": "*"
}
};
// Request body
const body = JSON.stringify({ name, email, password });
axios
.post('/api/users', body, config)
.then(res =>
dispatch({
type: REGISTER_SUCCESS,
payload: res.data
})
)
.catch(err => {
dispatch(
returnErrors(err.response.data, err.response.status, 'REGISTER_FAIL')
);
dispatch({
type: REGISTER_FAIL
});
});
};
The user sign up should be sending a name, email and password to my connected Mongo db, however, it halts me and redux hits the REGISTER_FAIL type I created returning the 431 error. Any help would be greatly appreciated. Thank you!
I had faced the same issue in my Angular Application. After spending a lot of time, I had found out that the issue is related with Node JS. We were using Node JS v12.x.x, and in this version, max-http-header-size reduced to 8KB from 80KB. And the auth token which I had was of around 10KB. That's why, when I reload the app, browser starts giving '431 request header fields too large' error for some of the files. I had updated the Node JS v14.x.x and it starts working again because in v14.0.0, max-http-header-size has been increased to 16KB.
Hope it will be helpful.
Another suggestion would be to access your cookies, in the inspector tool, and delete. applicable cookies for your localhost:{port} application.
I had similar problems with just using localhost(not limited to redux). Maybe this might help.
Put this into url: chrome://settings/?search=cache
Click on Clear Browsing data.
Tick cookies and other site data (Important since cookies is in HTTP header)
TIck cached images and files (might be optional)
Not reactjs, but using vue-cli, for people like me, just being stupid it may help:
I started my Vue app on port 8080, and my local backend was running at port 4000. However my requests pointed to 8080 and the response I got from Webpack Serving was "431 Request Header Fields Too Large".
The plain solution was just to use the right backend-port. Even though that was a really stupid mistake of me, the error message is kinda useless here.
It means you are trying to do this fetch on your current front-end development server. You need to specifiy the server address. For example:
.post('/api/users', body, config)
should read
.post('http://localhost:4000/api/users', body, config)
Another fix would be to change the line proxy in your package.json from localhost:3000 to localhost:4000 assuming that 4000 is your actual server port.
The issue I was having is that I was trying to access a file in the src directory. The fix is to move it to the public directory and it now works fine.
E.g.
From
public
- index.html
- favicon.ico
- etc
src
> access-me
- App.tsx
- etc
to
public
> access-me
- index.html
- favicon.ico
- etc
src
- App.tsx
- etc
Is it from Brad Travery's course? Check "proxy" in package.json, or try using full url in axios request. I had to completely restart server after changes, bc it's still use the old port (btw, I was enter wrong port)
Fixed in https://stackoverflow.com/a/56351573/9285308
(the max http header size parameter is configurable):
node --max-http-header-size 16000 client.js
In my react app, I add --max_old_space_size flag and it is worked. Current start script is :
"start": "react-scripts --expose-gc --max_old_space_size=12000 start",
Just change your start script in package.json file and you are good to go.
"start": "react-scripts --max-http-header-size=1024 start",
NextJS solution:
https://stackoverflow.com/a/73136780/6725458
"dev": "concurrently next dev node --max-http-header-size=64555 api-server"
Just found a solution:
NETCORE 6.0 / React template VS 2022
You have to setup the proxy url in package.json with the value of your url asp net application!
AspNet URL in debug console
So you can have that 431 error when you use the proxy of default React/AspNetCore project and you don't setup a proxy url (or a valid one) in the package.json.
proxy url in package.json
I had this problem when I accidentally created a proxy to the frontend itself by mixing up the port.
I had a backend on port 5000 and create-react-app on port 3000.
I put
"proxy": "http://localhost:3000",
in the package.json. This is clearly a mistake as it leads to infinite recursion by querying the react app over and over.
I fixed it (obviously) by putting the correct port number
"proxy": "http://localhost:5000",
Port numbers in your particular case might vary of course, just put this answer here for completess sake.

ExpressJS not sending Access-Control-Allow-Origin header

I am working on a project where I need an angular web app to be able to access a node/express based backend, and I am attempting to use Cors. However, the express server seemingly won't send the Access-Control-Allow-Origin header, and I have no clue why. I've tried creating a middleware as such:
this.app.use((request, response, next) => {
response.header("Access-Control-Allow-Origin", "*");
next();
}
I've also tried doing something similar individually for each request, using setHeader(), header(), set() and append(), but none of these work either. I'm currently using the cors npm package, but that also isn't working with the following code:
this.app.use(cors({
origin: "http://localhost/4200"
}));
this.app.options("*", cors({
origin: "http://localhost/4200"
})
);
I've checked that none of these are adding the relevant header to the response via postman. Express is adding the "error" header I use to give a human-readable description of the error, but not "Access-Control-Allow-Origin".
I'm writing this in TypeScript.
Did you restart your express server after making the change?
Did you try also adding the Access-Control-Allow-Headers header?
Did you check your middleware is invoked on request?
Did you check your middleware is registered before listen is called?
If both is guaranteed it must have a reason depending on a other part of your Application. So you should provide more information about booting and structure of files and directories.
Turns out the problem wasn't with the code, but with the compiler setup. I deleted and recreated the tsconfig.json file, and it works now.

On Ionic 2, XMLHttpRequest cannot load .. with Laravel api

This is my scenario:
XMLHttpRequest cannot load http://phi.dev/api/login. Redirect from 'http://phi.dev/api/login' to 'http://localhost:8100/' has been blocked by CORS policy: Request requires preflight, which is disallowed to follow cross-origin redirect.
I have a Aungular2/Ionic 2 App on local and a Laravel Web API for authenticating user.
if I call this Web API from my Angular2 Module, I get an exception as given above.
Note: In Chrome Network, I could my angular service is being called 2 times. First with Request Method: OPTIONS and second time with Request Method: Get, which returns Http 302.
Does anyone know how to resolve this issue.
Thanks in advance.
Because the request is external and because you are serving the application locally you will have CORS issues.
To avoid such issues locally (when using ionic serve), you have to setup a local proxy in the ionic configuration files.
Check your Ionic 2 project directory and locate the file ionic.config.json: it usually is in the root directory of the project (and need to be there, along with package.json and so on).
Open the file, and add this (do not forget to be SURE that the line BEFORE that one ends with a comma (,), since it's a json file):
"proxies": [
{
"path": "/server",
"proxyUrl": "http://phi.dev"
}
]
Now, in the section where are you are performing the HTTP request, replace the http://phi.dev with /server. I will give you an example here.
I do recommend you, however, to be aware that such edit will make your compiled app to NOT work, so you likely want to put a debug flag for testing and compiled environments, like this:
class MyServiceOrComponent {
private debug: boolean = true; // Set this flag to FALSE when you need to actually compile the app for any real device.
private server: string = this.debug ? "/server" : "http://phi.dev";
constructor(private http: HTTP) {
const login = "/api/login"; // don't to it exactly like that, make a static list or something like this to store paths.
let request = this.http.get(this.server + login).then((res) => {
console.log(res);
});
}
}
What happens, explained briefly, is that if you perform the HTTP request as "localhost" it will throw you an exception (because of the CORS policy). Such will happen only when you are running the application in your testing environment (localhost). To avoid such, you provide a proxy, so that the request will be valid.

Resources