接下来用 Express 调用 js 动态 API

Next js dynamic API call with Express

我有一个这样设置的快速服务器:

app.get('/', (req, res) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    fetch('https://api.adzuna.com:443/v1/api/property/gb/search/1?app_id=1cd4129d&app_key=key&where=se16bx&distance=5&category=for-sale')
      .then(response => response.json())
      .then(data => {
          res.send(data) // Prints result from `response.json()` in getRequest
      })
      .catch(error => console.error(error))
  });

然后我有一个 Next.js 页面,如下所示:

class About extends Component {
  state = {postcode: null}

  handleOnSubmit = e => {
      // calling the api passing the postcode
  }

  render() {
   return(
    <form>
      <input name="postcode" />
      <button onClick={this.handleOnSubmit}></button>
    </form>
   )
  }
}

About.getInitialProps = async function() {
  const res = await fetch('http://localhost:3001/');
  const data = await res.json();

  return {
    results: data
  }
}

Express 服务器中的 API 调用有一个硬编码的邮政编码。

where=se16bx

如何根据用户将输入到表单中的内容以动态方式传递该值?

谢谢

是的,您可以创建动态 API 调用,您可以从 here 查看完整的文档(检查 /posts API)。

在你的情况下,你只需要将 slug 添加到你的端点,然后将它传递给你的 fetcher 函数:

app.get('/:id*', (req, res) => {
res.setHeader('Access-Control-Allow-Origin', '*');
    fetch(`https://api.adzuna.com:443/v1/api/property/gb/search/1?app_id=1cd4129d&app_key=key&where=${req.params.id}&distance=5&category=for-sale`)
      .then(response => response.json())
      .then(data => {
          res.send(data) // Prints result from `response.json()` in getRequest
      })
      .catch(error => console.error(error))
  });