What should I use instead of localhost to deploy a React App? - reactjs

Please, I have this piece of code for a Contact Form in a React APP.
It works fine locally, but after I deploy it doesn't work. I guess I have change the localhost for something else, but for what?
Let's say that my domain is https://www.something.com.
What should I use instead of localhost to deploy my React App?
Error message that I receive if I keep the localhost domain: NetworkError when attempting to fetch resource.
PS.: The website works perfectly as well (locally and after the deploy). What I am trying here is to receive an answer of my fetch method (for my contact form) that it's not working.
fetch('http://localhost:5500/contact', {
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=utf-8',
},
body: JSON.stringify(details),
})

Whatever server backend you are running on port 5500 needs to be hosted online too. At the moment you just have your frontend hosted.
Once you have your backend hosted, change your fetch URL to that instead.

have you added the homepage props into the package.json file.?

Related

add custom ca-bundle to next.js for server side calls

I have my site domain.com hosted on Vercel. The next.js application talks to a Laravel API deployed at a subdomain.domain.com on AWS for server-side rendering.
I bought a separate SSL certificate for the wildcard domains and added the CAA entries to the DNS for the CA authorities. I see the certificate verified and working fine in the browsers. However, the server-side rendering requests were failing with the following error (local development connecting to the API hosted at subdomain)
event - build page: /user/[profile_id]
wait - compiling...
event - compiled successfully
Error: unable to verify the first certificate
at TLSSocket.onConnectSecure (_tls_wrap.js:1321:34)
at TLSSocket.emit (events.js:210:5)
at TLSSocket._finishInit (_tls_wrap.js:794:8)
at TLSWrap.ssl.onhandshakedone (_tls_wrap.js:608:12) {
code: 'UNABLE_TO_VERIFY_LEAF_SIGNATURE',
config: {
url: 'https://subdomain.domain.com/api/account/john-doe',
method: 'get',
headers: {
Accept: 'application/json',
Authorization: '',
token: '',
'User-Agent': 'axios/0.21.1'
},
.
.
I came across this package ssl-root-cas, and the issue is fixed (local development) and the pages load fine.
added this snippet to next.config.js
'use strict';
var rootCas = require('ssl-root-cas').create();
rootCas.addFile(__dirname + '/domain.ca-bundle');
// default for all https requests
// (whether using https directly, request, or another module)
require('https').globalAgent.options.ca = rootCas;
However, this doesn't seem to be working when I deploy to my staging site on Vercel.
My guess is Vercel doesn't have the domain.ca-bundle file? The file is added to the git version control, so should exist in the codebase when the build is generated.

Heroku: Django backend is not working, getting error GET http://localhost:8000/api/todos/ net::ERR_CONNECTION_REFUSED

I actually created a fullstack todo app with django as backend and react as frontend. The frontend is working perfectly fine, you can that here -> https://ym-todo-application.herokuapp.com. But somehow my application cannot connect to the django backend, also on inspecting on browser i saw this error -> GET http://localhost:8000/api/todos/ net::ERR_CONNECTION_REFUSED.
Containing lot of files and code so i pushed them on bitbucket to make it easier to debug. here's the link https://bitbucket.org/Yash-Marmat/todo-app-fullstack/src/master/.
Thanks in advance.
You need to change the REST API server address. The localhost:8000 is the server address used in the development.
What is more, I see in your code that each time you write the request you have hard-coded server URL. You don't need to do this. You can set the server address by setting baseURL:
import axios from "axios";
if (window.location.origin === "http://localhost:3000") {
axios.defaults.baseURL = "http://127.0.0.1:8000"; // development address
} else {
axios.defaults.baseURL = window.location.origin; // production address
}
Then in the request, you only write the endpoint address, example:
axios.put(`/api/todos/${item.id}/`, item)
Please see my article Docker-Compose for Django and React with Nginx reverse-proxy and Let's Encrypt certificate for more details about Django and React deployment.

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.

Opening up Rails API to users within a closed network

I am attempting to run a React/Rails Website locally for 2-3 users within a closed network. Currently, the users can reach the React portion (I have that set to port 80). The problem is, the API calls I have set to my Rails backend are all on localhost:3001 and the users have zero access to that database when I try to submit HTTP requests.
I know it's a CORS issue but I thought the code below would allow any domain to make the necessary request.
Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*'
resource '*',
headers: :any,
methods: [:get, :post, :put, :patch, :delete, :options, :head]
end
end
Server side work is not my forte, so I may be missing something glaring. Any idea how to open up that backend so the networked users can make API Calls on their end?
React is on this ip: http://192.168.2.70:80/
API calls on this port: 3001
Example API call from front end (works on host computer; not on other users):
getData = () => {
axios.get('http://localhost:3001/api/v1/pickup_deliveries')
.then((response) => {
this.setState({
apiData: response.data})
})
.catch((error)=>{console.log(error);});
}
The Problem
Unless I missed something, it looks like you're making a simple mistake that you're going to smack yourself for.
Typically, a CORS issue in a JavaScript application would yield a CORS/pre-flight request error error in your browser's JavaScript console.
The Misconception
The JavaScript that makes up a React application is downloaded by the client (i.e. your users). After that, the fetch call is executed on the client's computer. The fetch request doesn't originate from the server, but rather from the remote end.
It works on your computer because both React and the Rail API are hosted on your computer, so localhost:3001 resolves correctly. However, on your users computer, the React app attempts to find a service running on port 3001 on their computer.
Initial Solution
You need to tell React to reach out to the IP server that's hosting the API, like this:
getData = () => {
axios.get('http://192.168.2.70:3001/api/v1/pickup_deliveries')
.then((response) => {
this.setState({
apiData: response.data})
})
.catch((error)=>{console.log(error);});
}
Long Term Solution (for deployment)
In the future, look into dotenv, which will allow you to set React environment variables. You could have a .env.local file, and a .env.production file.
In the local file, you could put:
REACT_APP_BACKEND_SERVER=http://localhost:3001
and in the production on you could put:
REACT_APP_URL=http:/<server_ip>:3001
Then, in your program, do something like:
getData = () => {
axios.get(process.env.REACT_APP_SERVER_URL + "/api/v1/pickup_deliveries")
.then((response) => {
this.setState({
apiData: response.data})
})
.catch((error)=>{console.log(error);});
}
This will automatically resolve to localhost when serving React using npm run start and then resolve to <server_ip> when you are serving the static files generated by npm run build.
Feel free to comment on this answer. I would be happy to answer any other questions you have. Welcome to React!

React app using API with another origin (CORS)

I have a react app, which uses a java ee backend rest server, running on another domain. I have enabled CORS:
Access-Control-Allow-Origin : http://localhost:3000
Access-Control-Allow-Headers : origin, content-type, accept, authorization
Access-Control-Allow-Credentials : true
Access-Control-Allow-Methods : GET, POST, PUT, DELETE, OPTIONS, HEAD
Access-Control-Max-Age : 1209600
I am using react with fetch like this:
export function get(path, headers) {
return fetch(apiUrl + path, {
"metod" : "GET",
"headers" : headers,
"credentials" : "include"
})
}
My react app is running on http://localhost:3000.
When I am logging in, the server returns the Set-Cookie, but the cookie is not included in any further request to the server, unless I try to log in again. Then it is included for that specific login request.
Any suggestions?
I just want to share how I make my local development painless by this post if you are using create-react-app by just adding your main API url proxy to your package.js for example "proxy": "http://localhost:8080/API"
No need to setup CORS on your backend.
Install this.
https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=es
Once installed, click on his BrowserIcon and toggle on. It is all. You will not receive more error.
EDIT. Solution for Production
If you want config it from your server (or simply not adding a browser extension, try this:)
If you are using node.js do the following: node.js server file: response.writeHead(200, { 'Content-Type': contentType, 'Access-Control-Allow-Origin': '*' })
fetch('http://ajax.googleapis.com/ajax/services/feed/load?v=‌​1.0&num=8&q=http://r‌​ss.cnn.com/rss/editi‌​on_entertainment.rss‌​?output=rss', { method: 'get', mode: 'no-cors', }).then(() => { console.log('Works!'); });
Other solution:If you are using PHP too you can add: <?php header('Access-Control-Allow-Origin: *'); ?> into your PHP File. As I see, it is not the case, so... In your server (eg: Apache) add this directive: Header set Access-Control-Allow-Origin * in Settings (as the first option).
So, I solved the problem by using another stackoverflow thread and robertklep's comment. As stated here: "When working on localhost, the cookie domain must be omitted entirely.". I implemented robertkleps idea, but did not set the domain. It resulted in a Set-Cookie like this: Set-Cookie:kek=7fukucsuji1n1ddcntc0ri4vi; Version=1; Path=/; Max-Age=100000. This works fine.
To add more on existing answers.
With react you can use "proxy" in your package.json to avoid CORS.
Basically if you need to reach localhost:8100 (your java backend) and your react app run on localhost:3000
You can set:
In your package.json
"proxy": "http://localhost:8100"
And then when you want to make a get to /hello which would be an endpoint of your java API you can do:
import axios from 'axios';
axios.get('/hello')
.then(resp => {
console.log(resp.data);
});
And it will be redirected to http://localhost:3000/hello so you will avoid CORS.

Resources