首页 > 解决方案 > 无法使用 javascript fetch api 发布到 typicode json 服务器

问题描述

我有一个反应项目,我尝试将 JSON 对象发布到我的 Typicode 模拟 json 服务器。https://github.com/typicode/json-server#getting-started

提取失败,但我无法确定问题所在。也许 fetch 调用有问题,我想知道为什么以及如何解决它。

这是调用 fetch 方法的反应组件。

import React from "react";

class AddAnimal extends React.Component {
  constructor(props) {
    super(props);
    this.state = { animal: "animal", amount: 0, price: 0, sound: "sound" };
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <input
          type="text"
          name="animal"
          value={this.state.animal}
          onChange={this.handleOnChange}
        />
        <input
          type="number"
          name="amount"
          value={this.state.amount}
          onChange={this.handleOnChange}
        />
        <input
          type="number"
          name="price"
          value={this.state.price}
          onChange={this.handleOnChange}
        />
        <input
          type="text"
          name="sound"
          value={this.state.sound}
          onChange={this.handleOnChange}
        />
        <input type="submit" className="btn" value="add Animal" />
      </form>
    );
  }
  handleOnChange = e => {
  this.setState({[e.target.name]: e.target.value} );
  console.log(this.state);
  };

  handleSubmit = e => {
      e.preventDefault();
    if(this.state.amount === 0 || this.state.animal === "" || this.state.price === 0 || this.state.sound === ""){
        alert("you need to put information in all fields!");
        return false;
    }
    this.props.post(this.state);
  }
}

export default AddAnimal;

这是作为道具传递给 AddAnimal 组件的 fetch 方法。

  postAnimal(animal) {
    fetch("https://localhost:3000/animals", {
      method: "POST",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json"
      },
      body: JSON.stringify(animal)
    }).then(response => {
      console.log(response.json());
    })
  }

这就是数据库的外观和结构。这是为了显示 JSON 在发布之前必须采用的格式。

{
  "animals": [{
      "animal": "dogs",
      "sound": "woof!",
      "amount": 20,
      "price": 200
    },
    {
      "animal": "cats",
      "sound": "meow!",
      "amount": 15,
      "price": 150
    },
    {
      "animal": "horses",
      "sound": "yhgighighrr",
      "amount": 4,
      "price": 950
    }
  ]
}

这是我在输入详细信息后尝试提交表单时浏览器提示我的错误。

App.js:36 OPTIONS https://localhost:3000/animals net::ERR_CONNECTION_CLOSED
postAnimal @ App.js:36
AddAnimal._this.handleSubmit @ addAnimal.jsx:51
callCallback @ react-dom.development.js:147
invokeGuardedCallbackDev @ react-dom.development.js:196
invokeGuardedCallback @ react-dom.development.js:250
invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:265
executeDispatch @ react-dom.development.js:571
executeDispatchesInOrder @ react-dom.development.js:596
executeDispatchesAndRelease @ react-dom.development.js:695
executeDispatchesAndReleaseTopLevel @ react-dom.development.js:704
forEachAccumulated @ react-dom.development.js:676
runEventsInBatch @ react-dom.development.js:844
runExtractedEventsInBatch @ react-dom.development.js:852
handleTopLevel @ react-dom.development.js:5025
batchedUpdates$1 @ react-dom.development.js:19904
batchedUpdates @ react-dom.development.js:2246
dispatchEvent @ react-dom.development.js:5105
interactiveUpdates$1 @ react-dom.development.js:19966
interactiveUpdates @ react-dom.development.js:2267
dispatchInteractiveEvent @ react-dom.development.js:5081

&&

localhost/:1 Uncaught (in promise) TypeError: Failed to fetch
Promise.then (async)        
postAnimal  @   App.js:36
AddAnimal._this.handleSubmit    @   addAnimal.jsx:51
callCallback    @   react-dom.development.js:147
invokeGuardedCallbackDev    @   react-dom.development.js:196
invokeGuardedCallback   @   react-dom.development.js:250
invokeGuardedCallbackAndCatchFirstError @   react-dom.development.js:265
executeDispatch @   react-dom.development.js:571
executeDispatchesInOrder    @   react-dom.development.js:596
executeDispatchesAndRelease @   react-dom.development.js:695
executeDispatchesAndReleaseTopLevel @   react-dom.development.js:704
forEachAccumulated  @   react-dom.development.js:676
runEventsInBatch    @   react-dom.development.js:844
runExtractedEventsInBatch   @   react-dom.development.js:852
handleTopLevel  @   react-dom.development.js:5025
batchedUpdates$1    @   react-dom.development.js:19904
batchedUpdates  @   react-dom.development.js:2246
dispatchEvent   @   react-dom.development.js:5105
interactiveUpdates$1    @   react-dom.development.js:19966
interactiveUpdates  @   react-dom.development.js:2267
dispatchInteractiveEvent    @   react-dom.development.js:5081

标签: javascriptreactjsformsfetch

解决方案


typicode json-server 仅接受来自数据库的对象的 id,并且不适用于 https 连接。您需要验证您的后端,以使其正常工作。


推荐阅读