【问题标题】:Deleting items in mongodb using reactjs doesn't work使用reactjs删除mongodb中的项目不起作用
【发布时间】:2020-10-06 21:43:23
【问题描述】:

我使用 reactjs 作为前端,使用 expressjs 作为后端。 服务器被低功率勒索软件入侵,但并没有影响网站文件本身,但我不得不在 mongod 实例上添加防火墙以限制其他 IP 访问数据库,一切都很好,之后我尝试添加一个使用前端的数据库中的项目,它工作正常读取数据工作并添加数据工作问题是删除时我使用邮递员删除请求发送并删除项目正常,当使用firefox开发工具时我编辑了我的请求删除特定项目并将其删除,但是在使用前端时,它什么也没做,没有发送请求,没有给我任何响应,没有状态代码,什么都没有。 前端:

class AdminCardComp extends Component {
  constructor(props) {
    super(props);
    this.state = {
        appartmentId: '' 
      };
    this.onChange = this.onChange.bind(this);
    this.handleRemove = this.handleRemove.bind(this);
  }
  onChange(e) {
    if (e.target.id === 'appartmentId') {
      this.setState({ appartmentId: e.target.value });
    }
}
  handleRemove(){
    this.props.delAppartment(this.state.appartmentId);
    /*axios.delete("http://172.105.245.241:3443/appartments/"+this.state.ID,{ params: { appartmendId: this.state.ID }} , {}).then(res => {
        console.log(res.data)
    })*/
  }
  render() {
    const appartmentRender = this.props.appartments.appartments.map((appartment) => {   
        var x = 1;
        return(    
            <Card>
              <CardImg top src={baseUrl + appartment.image[0].image} alt={appartment.name} />
              <CardBody>
                <CardTitle>Appartment Number: {x}</CardTitle>
                <CardText>Appartment Description: {appartment.description}</CardText>
                <CardText>Appartment Price: {appartment.price}</CardText>
              </CardBody>
              <CardFooter>
                  <CardText>App ID: {appartment._id}</CardText>
              </CardFooter>
            </Card>
        );
        x++;
    })
    return (
      <>
        <div className="container col-12">
            <div className="row row-content col-12 col-sm-6">
                {appartmentRender}
            </div>
            <div className="row row-content col-12 col-sm-6 justify-content-center">
                <Form onSubmit={this.handleRemove}>
                    <Row>
                        <Col>
                            <Input className="formBack" onChange={this.onChange} type="text" id="appartmentId" name="appartmentId" placeholder="Enter ID" innerRef={(input) => this.appartmentId = input} />
                        </Col>
                    </Row>
                    <Row>
                        <Col>
                            <Button className="offset-sm-3 col-sm-5 buttonmr formBackButton" type="submit" value="submit">Remove</Button>
                        </Col>
                    </Row>
                </Form>
            </div>
        </div>
      </>
    );
  }
}

delAppart 方法在 ActionCreators 文件中

export const delAppartment = (appartmentId) => (dispatch) => {
  const bearer = 'Bearer' + localStorage.getItem('token');
  return fetch(baseUrl + 'appartments/' + appartmentId ,{
    method: "DELETE",
    body: JSON.stringify({ "_id": appartmentId }),
    headers: {
      "Content-Type": "application/json"
    },
    credentials: "same-origin"
  })
  .then(response => {
    if(response.ok){
      return response;
    }else {
      var error = new Error('Error ' + response.status + ': ' + response.statusText);
      error.response = response;
      throw error;
    }
  },error => {
    throw error;
  })
}

鉴于在攻击之前一切正常,正如您在前端看到的那样,我尝试使用 axios,但没有任何改变 后端

appartRouter.route('/:appartmentId')
.options((req,res) => {
    res.sendStatus(200);
})
.get((req,res,next) =>{
    Appartments.findById(req.params.appartmentId)
    .then((appartment) => {
        res.statusCode = 200;
        res.setHeader('Content-Type', 'application/json');
        res.json(appartment);
    }, (err) => next(err))
    .catch((err) => next(err));
})
.delete((req,res,next) =>{
    Appartments.findByIdAndRemove(req.params.appartmentId)
    .then((resp) => {
        res.statusCode = 200;
        res.setHeader('Content-Type', 'application/json');
        res.json(resp);
    }, (err) => next(err))
    .catch((err) => next(err));
})

This is the networks tab when trying to remove an item i suspect the first one says it's a GET type and it should've been DELETE type i'm not sure

【问题讨论】:

    标签: reactjs mongodb express frontend backend


    【解决方案1】:

    这似乎是 CORS 的问题。我建议您阅读更多有关它的信息here

    此外,在 Chrome 开发工具的 Network 选项卡中提供有关网络请求的屏幕截图或更多信息也会很有帮助。

    【讨论】:

    • 我已经编辑了帖子,然后我在控制台中看到“TypeError: NetworkError when trying to fetch resources”
    • 3xx 代码表示重定向,因此您应该检查端点。这肯定是错误
    • 现在我在 OPTIONS 和 DELETE 500 上得到 204,起初我在项目 id 上未定义,然后得到 id 和状态 500
    • OPTIONS 上的 204 表示这是一个 CORS 问题。 Options 是一个飞行前请求,它验证服务器是否可以响应是否可以发送请求。
    • 是的,在这个问题上解决了很长时间后,我想我添加了一些错误以找出真正的错误,结果证明它是 cors 中被遗忘的 s 字母,然后将一个名为 corsOptions 的变量用作 corsOption上,但让我绊倒的是,这一切在黑客攻击之前都可以正常工作!我从字面上将所有内容都改回了正常状态,并在 fetch 中添加了一个模式:'cors',并在路由中添加了几个用于所有来源的 Acces-Control-Allow-Origin 标头和公开标头,这就是全部
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-12
    • 2019-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-06
    相关资源
    最近更新 更多