Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/408.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在Express server中将状态对象作为POST正文发送并接收为空_Javascript_Reactjs_Express_Post_Fetch Api - Fatal编程技术网

Javascript 在Express server中将状态对象作为POST正文发送并接收为空

Javascript 在Express server中将状态对象作为POST正文发送并接收为空,javascript,reactjs,express,post,fetch-api,Javascript,Reactjs,Express,Post,Fetch Api,我试图用我的React表单组件发出一个POST请求,将我的状态对象作为主体发送,但我将主体作为{}接收 我的表单组件将状态信息传递给我作为prop创建的另一个React组件(引导输入) 我将信息保存在家长的状态(我也在该状态下发布),所以这应该不是问题 我的表单组件: class AgregarReservaForm extends Component { constructor(props) { super(props); this.state = {

我试图用我的React表单组件发出一个POST请求,将我的状态对象作为主体发送,但我将主体作为{}接收

我的表单组件将状态信息传递给我作为prop创建的另一个React组件(引导输入)

我将信息保存在家长的状态(我也在该状态下发布),所以这应该不是问题

我的表单组件:

class AgregarReservaForm extends Component {

    constructor(props) {
      super(props);
      this.state = {
        titulo: ''
      }

      this.handleTitulo = this.handleTitulo.bind(this);
    }

    handleTitulo(event) {
      this.setState({titulo: event.target.value})
    }

    async handleSubmit(event) {
      event.preventDefault();
      let self = this;
      let response = await fetch('http://localhost:3001/reserva', {
        method: 'POST',
        body: JSON.stringify(self.state),
        headers: {
          'Content-Type': 'application/json; charset=utf-8'
        },
        mode: 'no-cors'
      });

      if(!response.ok) {
        throw new Error();
      }

    }

    render() {

      return (
        <form onSubmit={this.handleSubmit}>

          <InputText
            name="titulo" 
            value={this.state.titulo}
            onChange={this.handleTitulo}
          />
</form>

Consoloe.log(body)正在打印“{}”。

您需要绑定handleSubmit方法,以便访问正确的
并随后在其中显示状态

constructor(props) {
  super(props);
  this.state = {
    titulo: ''
  }

  this.handleTitulo = this.handleTitulo.bind(this);
  this.handleSubmit = this.handleSubmit.bind(this);
}

它在handleSubmit中打印了你的州吗。。?您还可以检查开发人员工具中的网络选项卡,查看哪些数据正在传递到您的API。是的,它在handleSubmit中打印find,并且我看到将相同的对象作为请求负载传递到我的API:(您需要
express.json()
middleware。您使用过body parser中间件吗?不要使用“no cors”模式。因为您使用“no cors”模式发送请求,所以您试图添加到前端JavaScript代码中的
内容类型:application/json;charset=utf-8
请求头实际上没有添加到请求中。这是当您使用“无cors”模式时,您显式选择的ngs。因此当
http://localhost:3001/reserva
服务器接收到POST请求,但接收到的MIME类型不正确。服务器不知道它获取的POST正文的MIME类型,因此不知道如何处理它。
constructor(props) {
  super(props);
  this.state = {
    titulo: ''
  }

  this.handleTitulo = this.handleTitulo.bind(this);
  this.handleSubmit = this.handleSubmit.bind(this);
}