javascript - 如何使用 Star Wars SWAPI API 从服务器搜索端点

标签 javascript node.js reactjs api express

我正在尝试向服务器端端点添加一个搜索查询,它调用 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!'))

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

最佳答案

您没有使用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) => { ... })

关于javascript - 如何使用 Star Wars SWAPI API 从服务器搜索端点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51828868/

相关文章:

javascript - 在 AngularJS 单元/集成测试中向 HTTP 服务器发出真实请求

javascript - React-Redux Dashboard 应用程序结构

javascript - 单击时强制将焦点保持在 anchor 上

javascript - 带有嵌套流的 flatMapConcat

mysql - Angular 7可以使用 Node js 'mysql'模块连接到mysql吗

node.js - 配置文件中缺少 Bluemix CF App Loggregator 端点

javascript - 函数不适用于 React.js 中的 onClick 事件

javascript - 了解 Redux 的基本实现 | prevState 是如何使用的?

javascript - 为什么使用 element.innerHTML 后事件监听器会停止工作?

javascript - 如何在AngularJS上实现 "all check"按钮