У меня есть реактивный проект, в котором я пытаюсь опубликовать объект JSON на моём json-сервере Typicode.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 в качестве реквизита.
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