Javascript TypeError:无法执行';获取';在';窗口';:具有GET/HEAD方法的请求不能有正文
我目前正在学习教程,并不断发现上面的错误。检查了项目的源代码,似乎没有什么问题。 我只是一个初学者,所以我没有尝试过改变代码,因为我知道的不多;只是尽力查找错误,但一无所获 获取错误位于此代码的底部Javascript TypeError:无法执行';获取';在';窗口';:具有GET/HEAD方法的请求不能有正文,javascript,reactjs,fetch,Javascript,Reactjs,Fetch,我目前正在学习教程,并不断发现上面的错误。检查了项目的源代码,似乎没有什么问题。 我只是一个初学者,所以我没有尝试过改变代码,因为我知道的不多;只是尽力查找错误,但一无所获 获取错误位于此代码的底部 import React, { Component } from 'react'; import { TextField, Button, Grid, Typography } from "@material-ui/core"; import { Link } from &quo
import React, { Component } from 'react';
import { TextField, Button, Grid, Typography } from "@material-ui/core";
import { Link } from "react-router-dom";
export default class RoomJoinPage extends Component {
constructor(props) {
super(props);
this.state = {
roomCode: "",
error: ""
}
this._handleTextFieldChange = this._handleTextFieldChange.bind(this);
this._roomButtonPressed = this._roomButtonPressed.bind(this)
}
render() {
return (
<Grid container spacing={1} align="center">
<Grid item xs={12}>
<Typography component='h4' variant='h4'>
Join a Room
</Typography>
</Grid>
<Grid item xs={12}>
<TextField
error = {this.state.error}
label = "Code"
placeholder = "Enter a Room Code"
value = {this.state.roomCode}
halperText = {this.state.error}
variant = "outlined"
onChange = {
this._handleTextFieldChange
}
/>
</Grid>
<Grid item xs={12}>
<Button variant = "contained" color = "primary" to = "/" onClick =
{this._roomButtonPressed}>
Enter Code
</Button>
</Grid>
<Grid item xs={12}>
<Button variant = "contained" color = "secondary" to = "/" component = {Link}>
Back
</Button>
</Grid>
</Grid>
);
}
_handleTextFieldChange(e) {
this.setState({
roomCode: e.target.value
})
}
我认为问题在于fetch是异步的,所以您必须在代码中声明它。您可以使用
async
和wait
来执行此操作
async _roomButtonPressed() {
const requestOptions = {
methods: "POST",
headers: {"Content-Type": "application/json" },
body: JSON.stringify({
code: this.state.roomCode,
}),
};
await fetch("/api/join-room", requestOptions)
.then((response) => {
if (response.ok) {
this.props.history.push(`/room/${this.state.roomCode}`)
} else {
this.setState({error: "Room not found."})
}
})
.catch((error) => {
console.log(error);
});
}
}
不是方法而是方法属性,而是使用
方法:“POST”
async _roomButtonPressed() {
const requestOptions = {
methods: "POST",
headers: {"Content-Type": "application/json" },
body: JSON.stringify({
code: this.state.roomCode,
}),
};
await fetch("/api/join-room", requestOptions)
.then((response) => {
if (response.ok) {
this.props.history.push(`/room/${this.state.roomCode}`)
} else {
this.setState({error: "Room not found."})
}
})
.catch((error) => {
console.log(error);
});
}
}