簡體   English   中英

如何使用 node.js(express) API 調用訪問搜索參數並在 React 前端提供服務

[英]How to access search params with node.js(express) API call and served on react front-end

技術棧- node.js(express) 服務器,react 前端

組件文件夾結構
--src
- 成分
- 應用程序
--App.js
--app.css
- 商業
--Business.js
--Business.css
--BusinessList
--BusinessList.js
--BusinessList.css
- 搜索欄
--img
--SearchBar.js
--SearchBar.css
--util
--yelp.js

我想發生什么
當用戶在“搜索企業”中輸入輸入並在“哪里?”中輸入輸入時並單擊“讓我們開始按鈕”,它應該檢索輸入的類別,例如:“披薩”和輸入的位置,例如:“丹佛”

換句話說,用戶應該能夠“搜索企業”並輸入位置“哪里”並過濾結果

這是如何工作的
單擊 Let's Go 按鈕時,它調用從 yelp.js 導入到 App.js 中的 yelp.js searchYelp 函數的 searchYelp 函數,它從調用 API 的快速服務器獲取端點“/api/hello”。

目前正在發生什么
所以目前沒有進行過濾,當你點擊“Let's Go”按鈕時,它會返回一個隨機企業列表
我有過濾代碼設置,我只是不知道如何實現它以使其正常工作......

這是代碼

搜索欄.js

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

class SearchBar extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            term: '',
            location: '',
            sortBy: 'best_match'
        }

        this.handleTermChange = this.handleTermChange.bind(this)
        this.handleLocationChange = this.handleLocationChange.bind(this)
        this.handleSearch = this.handleSearch.bind(this)

        this.sortByOptions = {
            'Best Match': 'best_match',
            'Highest Rated': 'rating',
            'Most Reviewed': 'review_count'
        };
    }

    getSortByClass(sortByOption) {
        if (this.state.sortBy === sortByOption) {
            return 'active'
        }
        return ''
    }

    handleSortByChange(sortByOption) {
        this.setState({
            sortBy: sortByOption
        })
    }

    handleTermChange(event) {
        this.setState({
            term: event.target.value
        })
    }

    handleLocationChange(event) {
        this.setState({
            location: event.target.value
        })
    }

    handleSearch(event) {
        this.props.searchYelp(this.state.term, this.state.location, this.state.sortBy)
        event.preventDefault()
    }

    renderSortByOptions() {
        return Object.keys(this.sortByOptions).map(sortByOption => {
            let sortByOptionValue = this.sortByOptions[sortByOption]
            return <li onClick={this.handleSortByChange.bind(this, sortByOptionValue)} className={this.getSortByClass(sortByOptionValue)} key={sortByOptionValue}>{sortByOption}</li>;
        })
    }

    render() {
        return (
            <div className="SearchBar">
                {this.searchYelp}
                <div className="SearchBar-sort-options">
                    <ul>
                        {this.renderSortByOptions()}
                    </ul>
                </div>
                <div className="SearchBar-fields">
                    <input onChange={this.handleTermChange} placeholder="Search Businesses" />
                    <input onChange={this.handleLocationChange} placeholder="Where?" />
                    <button className="SearchBar-submit" onClick={this.handleSearch}>Let's Go</button>
                </div>
            </div>
        )
    }
};

export default SearchBar;

應用程序.js

import React from 'react';
import BusinessList from '../BusinessList/BusinessList';
import SearchBar from '../SearchBar/SearchBar';
import Yelp from '../../util/yelp';
import './App.css';

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

    this.searchYelp = this.searchYelp.bind(this);
  }

  searchYelp(term) {
    Yelp.searchYelp(term).then((businesses) => {
      this.setState({ businesses: businesses })
    })
  }
  render() {
    return (
      <div className="App">
        <SearchBar searchYelp={this.searchYelp} />
        <BusinessList businesses={this.state.businesses} />
      </div>
    )
  }
}

export default App;

Yelp.js

const { default: SearchBar } = require("../components/SearchBar/SearchBar");

const Yelp = {
    searchYelp(term) {
    return fetch('/api/hello/:term')
        .then((response) => {
            console.log(response)
            return response.json()
        }).then((jsonResponse) => {
            console.log(jsonResponse)
            if (jsonResponse.businesses) {
                return jsonResponse.businesses.map((business) => {
                    return {
                        id: business.id,
                        imageSrc: business.image_url,
                        name: business.name,
                        address: business.location.address1,
                        city: business.location.city,
                        state: business.location.state,
                        zipCode: business.location.zip_code,
                        category: business.categories.title,
                        rating: business.rating,
                        reviewCount: business.review_count,
                    }
                })
            }
        })
    }
}

export default Yelp

和服務器
我試圖過濾該術語只是為了測試但沒有成功,如果我能讓術語和位置正常工作,我認為我會很好,並省略 sortBy... Server.js

const express = require('express');
const axios = require('axios');
require('dotenv').config();
const cors = require('cors');
const bodyParser = require('body-parser');

const app = express();
app.use(cors());
const port = process.env.PORT || 5000;

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

const apiKey = process.env.APIKEY

app.get('/api/hello/:term', (req, res) => {
    const term = req.params.term
    const config = {
        method: 'get',
        url: 'https://api.yelp.com/v3/businesses/search?term=${term}&location=${location}',
        headers: {
            'Authorization': `Bearer ${apiKey}`
        }
    };

    axios(config)
        .then(function (response) {
            // res.send(JSON.stringify(response.data, null, 2));
            // res.send(term)
            return JSON.stringify(response.data, null, 2)
        }) 
        .then(function (jsonResponse) {
            res.send(jsonResponse)
        }) 
        .catch(function (error) {
            console.log(error);
        });
});

app.listen(port, () => console.log(`Listening on port ${port}`));

這是網絡應用程序的屏幕截圖
在此處輸入圖片說明

如果你想使用 yelp location過濾器的內置功能,你最好在你的 express 應用程序中表達它(雙關語!):

app.get('/api/hello/', (req, res) => {
    // use query instead of params,
    // and destruct location as well
    const {term, location} = req.query
    const config = {
        method: 'get',
        url: 'https://api.yelp.com/v3/businesses/search?term=${term}&location=${location}',
        headers: {
            'Authorization': `Bearer ${apiKey}`
        }
    };
}

...並在前端傳遞查詢參數:

const Yelp = {
    // take care to update any existing calls
    // to this function with the location parameter
    searchYelp(term, location) {
        return fetch(`/api/hello?term=${term}&location=${location}`)
        // etc. etc. ...

如果您只想在前端對其進行過濾(不推薦),並且位置輸入將始終包含一個城市名稱(並且您可以強制執行它)-您就快到了,剩下要做的就是聲明新的函數參數,並過濾結果:

function searchYelp(term, location, sortBy) {
  // ...
  this.setState({ businesses: businesses.filter(business => business.city === location) })
  // ...
}

如果您仍然不想使用 yelp API 的location ,並且想要更模糊的搜索(即能夠提供一般術語,如“brooklyn”,並輸出准確的信息,如城市、州、郵政編碼等),您必須在位置輸入上實現某種自動完成機制,這將涉及對某些后端服務的進一步調用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM