服务器未在 JSON 中返回数据

Server not returning data in JSON

我正在尝试使用 Node.js 作为后端并在前端使用 React 进行简单的 API 调用。我的 Node.js 文件没有返回 JSON 中的数据,我不确定为什么。我需要两件事的帮助:

  1. 为什么我的服务器在 JSON 中没有返回数据?
  2. 万一它开始返回上面的内容 JSON 我的 API 调用正常吗?

错误信息:

react-dom.development.js:14757 未捕获错误:对象作为 React 子项无效(找到:[object Promise])。如果您打算渲染子集合,请改用数组。 在 throwOnInvalidObjectType(反应-dom.development.js:14757:1) 后端使用的代码:

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);

前端代码(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()})

使用http调用本地服务http://localhost:8000/。测试服务器端,即邮递员或 curl 请求中的节点服务调用。前任。 curl -I http://localhost:8000/ 在与 React 集成之前。

您的节点脚本有一些错误。 res.json 在 express 节点模块中可用,但在 http 模块中不可用。

查看更新后的代码和样本输出

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

示例输出:

curl http://localhost:8000/

[{"number":1,"name":"CR7","gender":"male"},{"number":2,"name":"LEO","gender":"male"}]%     

   

Content-Type 在服务器代码中应该是 application/json

onClick="{fetcher()}" 更改为 onClick="{fetcher}",因为您希望仅在单击按钮时调用它,而不是立即在渲染时调用。 我还建议将函数移动到 return 之上,以便更好地组织代码。 正如上面提到的 Senthil,您可能还需要在 API 调用中使用 http 而不是 https