【问题标题】:React Router Adds URL Query Params on POST RequestReact Router 在 POST 请求中添加 URL 查询参数
【发布时间】:2021-05-13 21:12:21
【问题描述】:

你好,我的书呆子们,

我遇到了一个问题,当我发出 POST 请求(使用 React 函数内的 Axios 库)时,它会自动附加“提交时,在页面 URL 中的搜索参数中创建“用户”表单。我不喜欢这个,因为我希望它隐藏在 POST 请求中,而不是扔到页面 URL 上。

图片:URL after user was created

这是 React Router 将请求中发送的数据添加到响应路由器历史对象的 location.search 中的直接结果。因此,很自然,由于 react 路由器历史对象是可变的,我尝试将其添加到提交的响应中:

this.props.location.search.replace({*some random parameter stuff here*});

这是希望它能从 URL 中删除所有这些内容并重定向到没有搜索参数的页面。无论如何,我看过其他一些性质类似的帖子,但他们似乎没有回答这个确切的问题。

TL;DR:我正在尝试发送 POST 请求,但没有 React Router 将我的 req.body 数据添加到我的 URL 和 location.search 对象中的参数中。

我的密码:

Users.js:(前端)

handleSubmit (e) {
    Axios.post(`${server}/s/admin/users/create`, {
        headers: {
            'Content-Type': 'application/json'
        },
        data: {
            firstName: this.state.firstName,
            lastName: this.state.lastName,
            username: this.state.username,
            password: this.state.password,
            email: this.state.email
        }
    }).then((res) => {
        console.log(res);
    }).catch(err => console.log(err));
}

users.js:(后端)

app.post("/s/admin/users/create", (req, res) => {
let rb = req.body.data;
let newUser = new User({
    _id: uid.time(),
    orgID: req.session.orgID,
    email: rb.email,
    username: rb.username,
    password: bcrypt.hashSync(rb.password, hashRate),
    firstName: rb.firstName,
    lastName: rb.lastName,
    data: { exist: "true" },
    settings: { exist: "true" }
});

// Save new owner to db
newUser.save((err, data) => {
    if (err) return console.error(err);
    res.json({info: `A new user, ${newUser.firstName} ${newUser.lastName}, has been created successfully.`});
});

});

谢谢!

附:这是我的第一篇文章,感谢您的耐心等待。我已经尝试搜索和解决这个问题大约一天了。

【问题讨论】:

  • 你能分享一下你的组件代码在哪里写的吗?

标签: javascript reactjs express react-router axios


【解决方案1】:

你可以尝试用这种方式重写它吗?导致 axios.post 期望

axios({
  method: 'post',
  url: `${server}/s/admin/users/create`,
  headers: {
    'Content-Type': 'application/json'
  },
  data: {
    firstName: this.state.firstName,
    lastName: this.state.lastName,
    username: this.state.username,
    password: this.state.password,
    email: this.state.email
  }
}).then((res) => {
  console.log(res);
}).catch(err => console.log(err));

axios.post 方法期望第二个参数作为数据但你已经传递了配置,另一种方法是在第三个参数中传递数据和配置。

handleSubmit(e) {
  Axios.post(`${server}/s/admin/users/create`, {
      firstName: this.state.firstName,
      lastName: this.state.lastName,
      username: this.state.username,
      password: this.state.password,
      email: this.state.email
    }, {
      headers: {
        'Content-Type': 'application/json'
      }
    }
  }).then((res) => {
  console.log(res);
}).catch(err => console.log(err));
}

【讨论】:

    猜你喜欢
    • 2017-01-16
    • 1970-01-01
    • 2017-08-23
    • 2020-05-11
    • 2018-08-14
    • 2017-01-31
    • 2018-10-15
    • 1970-01-01
    • 2019-10-19
    相关资源
    最近更新 更多