如何在 Fetch API 中发出 GET 请求来获取特定数据?

问题描述 投票:0回答:1

我是 React 新手,我正在尝试根据城市名称获取特定搜索结果。我有一个完全依赖于用户输入(城市名称)的变量,我想使用这个变量作为我的 URL 中的参数。我确信我的语法是错误的,我尝试用谷歌搜索,但我什么也听不懂。有人可以解释一下 Fetch API 是如何工作的吗?以及如何发出带参数的 GET 请求?这是我的代码-

const City1= useSelector(state=>state.City); // 使用 Redux

const myrequest= fetch('http://xxxx.xxxx.xxxx.xxxx/xxxx/:?{$City1}', { 方法:'GET',标头: {'Access-Control-Allow-Origin':'*','Content-Type':'application/json'} }) .then(response => { if (!response.ok) { throw new Error('网络 反应不好');返回response.json(); }) .then (用户数据 => { // 处理检索到的用户数据 console.log('User Data:', userData); }) .catch(error => { console.error('错误:', error); });;

我的错误-

无法加载资源:服务器响应状态为 404(未找到)

xxxx.js:66 错误:错误:网络响应不正常

我的服务器代码-

router.get("/:city_name",(req,res,next)=>{

    const city_name_code=req.params.city_name;
    schema.find({City:city_name_code}).exec()
    .then(doc=>{
    console.log(doc);
    res.status(200).json(doc); }) .catch(err=>{   console.log(err);   res.status(500).json({error:err}); //  return; });
reactjs fetch-api
1个回答
0
投票

看起来您使用了错误的模板字符串。在你的行中

 fetch('http://xxxx.xxxx.xxxx.xxxx/xxxx/:?{$City1}'

应该与后面的勾号 `` 和大括号 {} 外面的 $ 一起使用

fetch(`http://xxxx.xxxx.xxxx.xxxx/xxxx/:?${City1}`
后面的勾号告诉Javascript应该是一个要替换的变量,而且${}的顺序是相关的。

另一方面,网址是对的吗?这 ”:?”需要吗?

© www.soinside.com 2019 - 2024. All rights reserved.