http web client cannot receive http request body unless it is in HTML; Java, React #144237
Unanswered
evanr1234
asked this question in
Programming Help
Replies: 1 comment
-
Hi @evanr1234, It looks like you’re encountering two main issues:
Let’s tackle these step by step: 1. Issue with Response Body VisibilityThe issue seems related to how your server formats and sends the HTTP response. Your server's response must strictly adhere to the HTTP protocol. Specifically:
Fixed Server Response Code: public void Handler(Socket s) {
BufferedReader is;
PrintWriter os;
String request;
JSONObject JSO;
try {
// Create a JSON object
JSO = new JSONObject();
JSO.put("value1", "value 2");
// Read request from client
is = new BufferedReader(new InputStreamReader(s.getInputStream()));
request = is.readLine();
System.out.println("Request Text: " + request);
// Write response to client
os = new PrintWriter(s.getOutputStream());
os.print("HTTP/1.1 200 OK\r\n");
os.print("Content-Type: application/json; charset=utf-8\r\n");
os.print("Access-Control-Allow-Origin: *\r\n");
os.print("Access-Control-Allow-Headers: Content-Type\r\n");
os.print("\r\n"); // End of headers
os.print(JSO.toString()); // JSON body
os.flush();
os.close();
System.out.println("Response sent to client: " + JSO.toString());
} catch (IOException e) {
System.err.println("Error handling request: " + e.getMessage());
}
} 2. React Client SetupTo fetch and display the response in your React app, use the useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch("http://localhost:80", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log("Received data:", data);
// Use the data to populate your table
} catch (error) {
console.error("Error fetching data:", error);
}
};
fetchData();
}, []); 3. Debugging TipsIf you still see blank or missing bodies:
4. Populating React TableOnce the JSON object is received, you can use it to populate a React table. Here’s a simple example: const [tableData, setTableData] = useState([]);
useEffect(() => {
const fetchData = async () => {
const response = await fetch("http://localhost:80");
const data = await response.json();
setTableData([data]); // Assuming `data` is a single JSON object
};
fetchData();
}, []);
return (
<table>
<thead>
<tr>
<th>Key</th>
<th>Value</th>
</tr>
</thead>
<tbody>
{tableData.map((row, index) => (
Object.entries(row).map(([key, value]) => (
<tr key={index + key}>
<td>{key}</td>
<td>{value}</td>
</tr>
))
))}
</tbody>
</table>
); Final Notes
Let me know if you encounter further issues! 😊 |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Body
I am trying to eventually create and send JSON objects from a Java web server using the java.net packages, having my react web app receive the JSON object, and then use this object to populate the react table fields(useTable).
Preliminarily, I am trying to see if I can simply send a http response to this React client containing plain text, html, or JSON, and have the React page print the response body to the chrome browser console.
It seems the browser is only receiving response bodies if they are in HTML. Only the HTML bodies will print to the console, and also if I go to the chrome developer tools/network/click on request url I am able to see the body and headers ONLY if it is HTML(I know from viewing the response bodies in the chrome devtools). For plain text or JSON I see the headers with no body. For the "Content-Type" header I have used "text/plain", "text/html" and "application/json", using test strings such as "aslfjasdlfjasfdlj", the JSO object from my code, an JSO.toString() for the body.
The console displays a blank line when I enter free text into the body of the response, the HTML when I enter html, and "undefined" when I try to send a JSON object. In the chrome dev tools, it displays the request and response headers as shown:
Request Headers:
Accept:*/* Accept-Encoding:gzip, deflate, br, zstd Accept-Language:en-US,en;q=0.9 Connection:keep-alive Content-Length:0 Content-Type:text/plain Host:localhost Origin:http://localhost:3000 Referer:http://localhost:3000/ Sec-Ch-Ua:"Chromium";v="130", "Google Chrome";v="130", "Not?A_Brand";v="99" Sec-Ch-Ua-Mobile:?0 Sec-Ch-Ua-Platform:"macOS" Sec-Fetch-Dest:empty Sec-Fetch-Mode:cors Sec-Fetch-Site:same-site User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36
Response Headers:
Access-Control-Allow-Headers:Content-Type Access-Control-Allow-Origin:* Content-Type:text/plain; charset=utf-8 Server:http://localhost:80/
I am brand new to this practice and any feedback on general approach, along with resolving this issue will be of great help!
`var xr = new XMLHttpRequest();
` public class ServerRequests {
I tried on the safari browser, it had similar results except I didn't any input to console even for html. I tried using xr.response, xr.responseText with similar results. I tried different ports, with 8080 not working as well.
Guidelines
Beta Was this translation helpful? Give feedback.
All reactions