node.js - 如何使用 fetch API 解析 json 响应

标签 node.js reactjs express

我尝试使用 fetch 调用 API 后显示 json 响应,我可以在 chrome 的响应选项卡中看到响应,但在 fetch 响应对象中找不到它

客户端

   import React from 'react';
import './App.css';

class App extends React.Component {

  constructor(props) {
    super(props)
    this.state = {
      query: '',
      properties: []
    }
    this.search = this.search.bind(this);
    this.handleChange = this.handleChange.bind(this)
  }

  handleChange(event) {
    const { name, value } = event.target;
    // const { query } = this.state.query;
    this.setState({
      [name]: value
    });

  }


  search() {
    console.log('fetching data')
    try {
      fetch('http://localhost:3000/property/find', {
        method: 'POST',
        mode: 'CORS',
        body: JSON.stringify({ "query": this.state.query }),
        headers: {
          'Content-Type': 'application/json'
        }
      }).then(res => res.json())
        .then((data) => {
          console.log(data)
          this.setState({ properties: data.result });
        })

    }
    catch (err) {
      return err;
    }
  }


  render() {

    const { properties } = this.state;
    return (
      <div className="App" >


        <input type="text" name="query" onChange={this.handleChange}></input>

        <div className="form-group">
          <button className="btn btn-primary" onClick={this.search}>Search</button>
        </div>

        <div className="row text-center">

          {properties.items &&
            properties.items.map((property, index) =>
              <div className="col-lg-3 col-md-6 mb-4" key={index}>
                <div className="card h-100">
                  <img className="card-img-top" src="http://placehold.it/500x325" alt="" />
                  <div className="card-body">
                    <h4 className="card-title">  {property.details.description}</h4>
                    {/* <p className="card-text">{property.biography}</p> */}
                  </div>
                  <div className="card-footer">
                    <a href="#" className="btn btn-primary">Find Out More!</a>
                  </div>
                </div>
              </div>
            )

          }


        </div>


      </div>
    )

  }
}

export default App;

服务器端

var app = express();
const server = http.createServer(app);
const io = socketIo(server);

var db = require('./db');

var property = require('./endpoint/property');
// var authController = require('./auth/AuthController');


app.use(function (req, res, next) {
    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3001');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

    next();
});

//allow OPTIONS on just one resource
// app.post('*', cors())
app.use(cors())

app.use('/property', property);

终点响应

      var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');

router.use(bodyParser.urlencoded({ extended: true }));
router.use(bodyParser.json());

var Model = require('../model/propertyModel');


// GETS A SINGLE USER FROM THE DATABASE
router.post('/find',function (req, res) {
  var query = req.body.query

  console.log(query)


  Model.find(   {  $text: { $search: query }} ,  { score: { $meta: "textScore" } }).sort( { score: { $meta: "textScore" } } ).then((data)=>{

   if(data.length>0){

    res.status(200).json({"result":data});
   } 
   if (data.length==0){

    Model.find({ "details.description":  {$regex:query}  }).sort( { score: { $meta: "textScore" } } ).then((data)=>{

      if(data){
        res.status(200).json({"result":data});
       } 
       if (data.length==0) return res.status(404).send("No properties found.");



    })

   }


  })


});

enter image description here

enter image description here

enter image description here

最佳答案

在你的渲染方法中,如果你改变这个:

{properties.items &&
            properties.items.map((property, index) =>

...对此:

{properties &&
            properties.map((property, index) =>

这应该可以为您解决这个问题。

关于node.js - 如何使用 fetch API 解析 json 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59474200/

相关文章:

Javascript:SyntaxError:await 仅在异步函数中有效

reactjs - 监听 redux saga 中组件中的 reducer 状态变化

node.js - 在 Angular 中 POST 时表单数据是正确的,但 req.body 在 Node 中是空的?

node.js - 如何在Express中的单个路由处理程序中处理来自多个独立的Promise的错误?

javascript - 在 reactJS 中调用 fetch 时需要修改 onClick 函数中的 URL

javascript - 如何检查 node-cron 执行 cron-job 花费了多少时间

javascript - 转到另一个网址而不重新加载页面

javascript - 更改 Prop 时, react 表重新渲染不起作用

javascript - 如何从一组可渲染组件构建 JSX 组件树?

javascript - 如何限制API只在浏览器运行?