Spring + ReactJS ERRCONNRESET - reactjs

i am working on a ReactJS app with a Spring backend server which provides the data. The data is passed via Websockets. Some Snippets from the Spring side of things:
#Autowired
private SimpMessagingTemplate template;
.
.
EditorObject obj = new EditorObject();
template.convertAndSend("/update/editor", obj);
In the ReactJS part the websocket is connected via
const editorSocket = new SockJS("/websocket")
const editorClient = Stomp.over(editorSocket)
editorClient.debug = null
editorClient.connect({}, () => {
console.log("im connect")
editorSubscription = editorClient.subscribe("/update/editor", (msg) => {
// do sth
})
What i am trying to do is work on the project in the development mode via npm start. I added
"proxy": "http://localhost:8080"
to my package.json. Everything works fine in production but when I access the app via npm start on the port 3000 i get the following error in console:
Proxy error: Could not proxy request /websocket/602/m05cnhhq/xhr?t=1675349479939 from localhost:3000 to http://localhost:8080.
See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (ECONNRESET).
Any help is appreciated, having to build to see any changes applied is atrocious.
I have also researched a bit, this seems to be caused by my Spring server cutting the connection. I don't see anything in the server's output that looks anything like that. The only warning i get is
Resolved [org.springframework.http.converter.HttpMessageNotWritableException: No converter for [class java.util.LinkedHashMap] with preset Content-Type 'text/event-stream;charset=UTF-8']

Related

Trouble getting production build React application to make requests to Flask back-end

I have developed a React (front-end) and a Flask (back-end) application.
I have been using the command "npm start" to start the development version of the front-end. This is working fine. The front-end has no trouble sending "fetch" commands to the Flask back-end.
I need to get a production build of the React application running. The React application and the Flask server both need to be deployed locally on the same Linux box (I cannot use "Heroku", etc).
I have created a development build of the react application using the command "npm run build". After the build folder is created successfully, I can run the development build using the command "serve -s build"
The problem occurs when the production build React application attempts to communicate with the currently running back-end server using the fetch command.
The back-end server is set up to run on host = "localhost", port = 3001. The front-end is running on host = "localhost", port = 3000. For development purposes I installed "http-proxy-middleware" and then I created the file "src/setupProxy.js" with the following content:
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
app.use(createProxyMiddleware("/api_tpwa" , { target : "http://127.0.0.1:3001/"})); }
After doing a bit of research online I came to the conclusion that the current proxy can be used for development, but not in a production build
Here is an example of some test react code (that calls "fetch") that works in the react development application but fails in the production build (proxy is still being used in production build)):
fetch(`/api_tpwa/test`).then(response => {
console.log(response);
return response.json();
})
.then((data) =>
{
console.log(data);
})
.catch(error => {
console.log(error);
})
When I run this using the production build I get the following information printed for the "response" variable in the console:
Response { type: "basic", url: "http://localhost:3000/api_tpwa/test", redirected: false, status: 200, ok: true, statusText: "OK", headers: Headers, body: ReadableStream, bodyUsed: false }
I get the following information for the caught error in the console:
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
I compared the value for "response" for the development build (started with npm start) vs the production build and the values were identical. So, I'm not sure why there would be a json syntax error in one case and not in the other.
I suspect the problem is related to the use of the proxy within the production build but I'm not sure.
Here is the back-end route test function:
#app.route("/api_tpwa/test")
def routeTest():
print("executing api test()")
returnResult = {'result': 1}
return json.dumps(returnResult)
This back-end function never gets executed for the production build. the text "executing api test()" is not printed to the console.
What changes would I need to make to either the front-end or back-end to get a production build react app that can successfully communicate with the Flask back-end?
Any help would be greatly appreciated.

React app + heroku server not working on production, but working fine in dev

I am working on React application which is querying from a server. I have deployed the server on heroku. When I am testing in dev, the application is behaving as expected. But when I am using it on vercel deployment, it is failing as heroku server is not responding properly.
Following is the server code of the query:
app.get(`/allPlans`, async (req, res) => {
console.log("allPlans() query");
ret = await Plans.find({});
f = [];
for (i = 0; i < ret.length; i++) {
f.push(ret[i].name);
}
console.log(f);
return res.status(200).send(f);
});
Folowing is the code I am using to query from the client using axios:
const endPoint = "/allPlans";
let ret = await axios.get(endPoint);
console.log(ret.data);
In the dev environment, when I am deploying the application on localhost:3000, this is returning me a nice array.
["test","myPlan190","myPlan987"]
But in the actual production on vercel it is returning the following object(You can check this message in the console by going on the vercel deployment):
All suggestions are welcome.
Github repo
Vercel deployment
Server status
Heroku server query which is failing from axios, but working elsewise
Well, I checked you repository and also checked the XHR requests on your Vercel deployment and as far as I can see it making only one, which is:
Request URL: https://planner-pcrsehfg3-akcgjc007.vercel.app/allPlans
It is not making an actual call to the server. I see that in Dashboard.js you are requiring axios from the package. I did not find any created instance of axios. So essentualy there is nothing to append in front of "/allPlans". Either create an axios instance with the right url "https://cryptic-bayou-91116.herokuapp.com" of just test it by putting the whole url "https://cryptic-bayou-91116.herokuapp.com/allPlans" inside the axios call in Dashboard.js.
Following is the updated code for an axios query:
const baseURL = "https://cryptic-bayou-91116.herokuapp.com"
...
const endPoint = baseURL + "/allPlans";
let ret = await axios.get(endPoint);
console.log(ret.data);
fHeroku randomly changed application binding port.
You may set port by:
const port = process.env.PORT || 3000
for this use in you app dotenv
Or edit file .env on heroku. Install Heroku CLI:
heroku login
heroku run bash -a app_name
touch .env
echo "PORT=3000" >> .env
check variable by
cat .env

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.

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

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/

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

Resources