我的快递服务器设置如下:
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
如何根据用户要输入的表单以动态方式传递该值?
谢谢
答案 0 :(得分:1)
是的,您可以创建动态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))
});