'Server not returning data in JSON

I am trying to make a simple API call using Node.js as the backend and React in the frontend. My Node.js file is not returning data in JSON, and I am not sure why. I need help on 2 things:

  1. Why is my server not returning data in JSON?
  2. In case it starts returning the above JSON is my API call good to work?

Error msg:

react-dom.development.js:14757 Uncaught Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead. at throwOnInvalidObjectType (react-dom.development.js:14757:1) Code used on backend:

const http = require("http");
let user={"name":"Leo"};
var server = http.createServer(function(req ,res){
    res.writeHead(200, {'Content-Type': JSON});
   
    res.json([{
        number: 1,
        name: 'CR7',
        gender: 'male'
      },
      {
        number: 2,
        name: 'LEO',
        gender: 'male'
      }
    ]);
    res.end(" done");
});
server.listen(8000);

Code on the frontend(React):

import "./index.css";
function App() {
  return (
    <div className="App">
      <header className="App-header">
      <form>
  <div>
  <div className="form-group">
    <label htmlFor="exampleInputEmail1">Email address</label>
    <input type="email" className="form-control" />
    <small className="form-text text-muted">We'll never share your email with anyone else.</small>
  </div>
  <div className="form-group">
    <label>Password</label>
    <input type="password" className="form-control"/>
  </div>
  <div className="form-group form-check">
    <input type="checkbox" className="form-check-input" />
    <label className="form-check-label" >Check me out</label>
  </div>
  <button type="submit" onClick="{fetcher()}"  className="btn btn-primary">Submit</button>
</div>
      </form>
      {//using state
      }
      function fetcher(){
        fetch("https://localhost:8000/user.name",{
          headers : { 
            'Content-Type': 'application/json',
            'Accept': 'application/json'
           }
    
        })
        .then((data)=>{return data.json()})


Solution 1:[1]

Content-Type should be application/json in the server code.

Change onClick="{fetcher()}" to onClick="{fetcher}", cause you want it to be called only when you click on the button, not immediately on render. I also recommend moving the function above your return, for better organizing your code. As Senthil mentioned above, you might also need to use http and not https in your API call.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ron Hillel