Javascript 下一个使用Express的js动态API调用

Javascript 下一个使用Express的js动态API调用,javascript,reactjs,next.js,Javascript,Reactjs,Next.js,我的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=fo

我的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
  }
}
类关于扩展组件{
state={postcode:null}
handleOnSubmit=e=>{
//调用传递邮政编码的api
}
render(){
返回(
)
}
}
About.getInitialProps=异步函数(){
const res=等待取数('http://localhost:3001/');
const data=wait res.json();
返回{
结果:数据
}
}
Express服务器中的API调用包含硬编码的邮政编码

其中=se16bx

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


谢谢

是的,您可以创建动态API调用,您可以从中查看完整的文档(检查
/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))
  });