【问题标题】:Replace " " with %20 inside a fetchcall在 fetchcall 中将“”替换为 %20
【发布时间】:2020-02-12 12:22:49
【问题描述】:

我知道关于 如何用 %20 替换“”(空格) 的问题已经在 SO 上提出,但我需要知道在哪里可以实现它 - 我正在使用 React Native 作为我的前端和 NodeJS(ExpressJS) 作为我的后端连接到一个 PostgreSQL DB

是否可以使用bodyparser urlencoded 来实现这一点?我只需要在 1 或 2 个查询中使用它,而不是全部。

我的前端部分:(在 componentDidMount 上调用它)

  getData("username")
  .then(data => data)
  .then(value => {
    this.setState({username: value})
  fetch(`http://xxx.xxx.xx.xx:6969/api/hours/unlock/'${value}'`)    // replace " " mit %20 ?!?!?! 
  .then(res => res.json())
  .then(result => {
    console.log("** UuNamMe **" + this.state.username)
    console.log("Res from  UnlockTabelle : " + result)
    console.log("Res from  UnlockTabelle[0] : " + result[0])
  })
  .catch(err => console.log("ErrorLog: @unlock : " + err))
  })
  .catch(err => console.log(err))

我的后端部分:

  static unlockUser(username, callback) {
    db.query(`SELECT * FROM unlock WHERE name = '${username}'`, (err, res) => {
      if (err.error) {
        callback(err);
      }
      callback(res);
    });
  }

  static lockUser(username, callback) {
    db.query(`DELETE FROM unlock WHERE name = '${username}'`, (err, res) => {
      if (err.error) {
        callback(err);
      }
      callback(res);
    });
  } 

router.get("/unlock/:username", (req,res) => {
  const username = req.params.username
  Hours.unlockUser(username, (err, result) => {
    if(err) {
      return res.json(err)
    }
    return res.json(result)
  })
})

router.delete("/lock/:username" , (req, res) => {
  const username = req.params.username
  Hours.lockUser(username, (err, result) => {
    if(err) {
      return res.json(err)
    }
    return res.json(result)
  })
})

如果我想将 URL 编码为 用 %20 替换 " " 会发生什么情况?在我的后端使用 bodyparser 或在我的前端,如果是这样,那会是什么样子?

【问题讨论】:

  • 解锁我的用户名时出了点问题,请您检查一下。这是我的数据:var username = "'; SELECT * FROM pg_catalog.pg_tables WHERE '1' = '1"
  • 我不明白你的意思,但它现在仍然有效。
  • 不要相信小鲍比桌! xkcd.com/327
  • :D :D 是的,我明白你在说什么 - 如果我考虑保护我的应用程序,我是否需要在 postgreDB 或我的应用程序(前端或后端)内部进行清理 - ty
  • 不,不是前端,这只是你的后端可以做的事情。您最好的选择是使用准备好的语句。

标签: javascript node.js react-native express urlencode


【解决方案1】:

你可以在前端使用encodeURIComponent

fetch(`http://xxx.xxx.xx.xx:6969/api/hours/unlock/'${encodeURIComponent(value)}'`)

【讨论】:

  • 如果我从 ${value} 中删除 ' ' 似乎可以工作,但我会将其保留为备份。
【解决方案2】:

或者,您可以将相关的headers 添加到您的fetch 语句中,如下所示,

fetch(`http://xxx.xxx.xx.xx:6969/api/hours/unlock/'${value}'`, {
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
    }
})

希望这会有所帮助!

【讨论】:

  • 如果我从 ${value} 中删除 ' ' 似乎可以工作,但我认为我仍然会附加它以确保 ty
【解决方案3】:

好的,我刚刚注意到,如果我从 '${value}' 中删除 ' ',它实际上可以工作 - 检查空格并替换它们是否更好,因为这似乎以某种方式自动发生。

【讨论】:

    猜你喜欢
    • 2011-10-08
    • 1970-01-01
    • 2016-01-09
    • 2014-06-21
    • 1970-01-01
    • 2018-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多