【问题标题】:how to search endpoint from the server using Star Wars SWAPI API如何使用 Star Wars SWAPI API 从服务器搜索端点
【发布时间】:2019-01-20 13:40:35
【问题描述】:

我正在尝试向服务器端端点添加搜索查询,该端点调用 swapi - Star Wars API https://swapi.co/ 并按姓名列出人员。

这是 App.js 中对后端的 fetch 调用的样子(我为此使用了 reactJS 框架):

import React, { Component } from 'react';

class App extends Component {
  constructor() {
    super();
    this.state = {
      searchResult: [],
    }
  }

    searchPersonByName = (event) => {
    fetch('/people/?search='+ event.target.value)
      .then(response => response.json())
      .then(response => {
        //let searchResult = JSON.parse(responseBody).results;
        console.log(response);
        this.setState({ searchResult: response.results });
      })
  }
render() {
    return (
      <div className="pageStyle">
        <div className="searchBar">
          <input type="text"
            placeholder="search for a person"
            onChange={this.searchPersonByName}>
          </input>
          {Object.keys(this.state.searchResult).map((item, i) => (
            <li key={i}>
              <span>{this.state.searchResult[item].name}</span>
            </li>
          ))}
        </div>
      </div>
    );
  }
}

export default App;

在后端:

    //Dependencies
    const swapi = require('swapi-node');
    const express = require('express'); //express server
    const app = express();

    app.use(express.static('public'))

    //Search people endpoint
    //format of the search string:
    // https://swapi.co/api/people/?search=
    app.get('/people', (req, res) => {
    let query = req.query.search;
    console.log(query);
    swapi.get('https://swapi.co/api/people/?search=' + query).then((result) => {
        console.log(result.results);
        let results = result.results;
        res.send({ results });
    }).catch((err) => {
        console.log(err);
    });
});
//server listening on specified port
app.listen(4000, () => console.log('Listening on port 4000!'))

现在搜索查询只返回第一页的人。缺少什么?

【问题讨论】:

    标签: javascript node.js reactjs api express


    【解决方案1】:

    您没有通过 fetch 请求将搜索词传递到后端。

    如果你真的想搜索输入字段中的每一个变化,你可以使用event.target.value作为搜索词。

    searchPersonByName = event => {
      fetch(`/people?search=${event.target.value}`)
        .then(response => response.json())
        .then(response => {
          this.setState({ searchResult: response.results });
        });
    };
    

    您也不需要在后端路由中指定查询参数。

    app.get('/people', (req, res) => { ... })
    

    【讨论】:

    • 感谢@Tholle。那么服务器端查询是否如下所示:app.get('/people/?search=$event.target.value', (req, res) =&gt; { swapi.get('https:swapi.co/api/people/?search=$event.target.value').then((result) =&gt; { ... });
    • @ksenia 抱歉,我忘记了。我更新了答案。
    • 好的,但是swapi.get 端点字符串是什么样子的?
    • @ksenia swapi.get 看起来 like the documentation。你现在试过了吗?
    • 如果你很好奇,问题出在代理上。 http vs https...现在解决了!
    【解决方案2】:

    在 App.js 中获取调用

    import React, { Component } from 'react';
    
    class App extends Component {
      constructor() {
        super();
        this.state = {
          searchResult: [],
        }
      }
    
        searchPersonByName = (event) => {
        fetch('/people/?search='+ event.target.value)
          .then(response => response.json())
          .then(response => {
            //let searchResult = JSON.parse(responseBody).results;
            console.log(response);
            this.setState({ searchResult: response.results });
          })
      }
    
    render() {
        return (
          <div className="pageStyle">
            <div className="searchBar">
              <input type="text"
                placeholder="search for a person"
                onChange={this.searchPersonByName}>
              </input>
              {Object.keys(this.state.searchResult).map((item, i) => (
                <li key={i}>
                  <span>{this.state.searchResult[item].name}</span>
                </li>
              ))}
            </div>
          </div>
        );
      }
    }
    
    export default App;
    

    和后端:

    //Dependencies
    const swapi = require('swapi-node'); 
    const express = require('express'); //express server
    var bodyParser = require('body-parser');
    const app = express();
    
    app.use(express.static('public'));
    app.use(bodyParser.json({ type: 'application/json' }));
    
    var API_URL = 'http://swapi.co/api/';
    
    //Search people endpoint
    //format of the search string:
    // https://swapi.co/api/people/?search=
    app.get('/people', (req, res) => {
        let query = req.query.search;
        console.log(query);
        swapi.get('http://swapi.co/api/people/?search=' + query).then((result) => {
            console.log(result.results);
            let results = result.results;
            res.send({ results });
        }).catch((err) => {
            console.log(err);
        });
    });
    
    //server listening on specified port
    app.listen(4000, () => console.log('Listening on port 4000!'))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-24
      • 2020-06-07
      • 2017-10-02
      • 2017-08-24
      相关资源
      最近更新 更多