不确定我的代码是怎么回事,但是我试图通过axios控制台进行测试运行以注销某些内容,但是我得到了404。
class SubscribeForm extends Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.emailChange = this.emailChange.bind(this);
this.emailSubmit = this.emailSubmit.bind(this);
}
emailChange(e) {
this.setState({value: e.target.value});
}
emailSubmit(e) {
e.preventDefault();
axios.post('/subscribe', {
email: 'someemail@email.com',
headers: {
'Content-Type': 'application/json;charset=UTF-8',
"Access-Control-Allow-Origin": "*",
}
}).then(res => {
if(res.data.success) {
this.setState({email: ''})
}
}).catch(error => {
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
console.log(error.config);
});
}
render() {
const { classes } = this.props;
return (
<div className={classes.subFormSection}>
<p className={classes.formHelper}>
Join the club, enter your email address
</p>
<form method="post" className={classes.subFormWrap} onSubmit={this.emailSubmit}>
<TextField
value = {this.state.value}
onChange = {this.emailChange}
/>
<Button
className={classes.button}
type="submit"
>
Send
<Icon className={classes.rightIcon}>send</Icon>
</Button>
</form>
</div>
);
}
}
我尝试将标题添加到axios中以查看是否是问题所在,但我不认为这是问题所在(或者我做错了)。
此外,我没有/ subscribe文件,我认为我不需要一个文件吗?因为,我在这里用express捕获它:
const cors = require("cors");
app.use(cors());
app.post("/subscribe", (req, res, next) => {
console.log(req.body.email);
});
此文件位于我的服务器文件中,而react部分位于客户端文件中。我已经设置了代理,因此当我运行服务器时,前端和后端正在互相通信。
已更新的404状态变为(待处理)
我还在客户端文件夹setupProxy.js
中设置了代理中间件
const proxy = require("http-proxy-middleware");
module.exports = function(app) {
app.use(proxy("/subscribe", {
target: "http://localhost:5000"
}));
};
我在网络请求/subscrib
中进入了请求标头:
Provisional headers are shown
这是否导致(待处理)?
答案 0 :(得分:2)
据我所见,您的服务器和客户端应用程序似乎在不同的端口上运行。如果是这种情况,您将无法执行以下操作:
axios.post('/subscribe', {
email: 'someemail@email.com',
headers: {
'Content-Type': 'application/json;charset=UTF-8',
"Access-Control-Allow-Origin": "*",
}
})
您正在使用没有主机的路径/subscribe
。 Axios尝试使用运行客户端应用程序的主机,但找不到该路径,因此找不到404
状态代码。
在这种情况下,可以使用/subscribe
路径之前的服务器的主机和端口来修复它。见下文:
axios.post('localhost:4000/subscribe', {
email: 'someemail@email.com',
headers: {
'Content-Type': 'application/json;charset=UTF-8',
"Access-Control-Allow-Origin": "*",
}
})
请将此处localhost:4000
的端口更改为服务器端口。
注意:这仅用于您的本地开发。
如果计划部署应用程序,则可能要使用process.env.PORT
。
答案 1 :(得分:0)
您可以使用浏览器的检查元素检查请求是否正确发出(检查元素>网络)。
通过查看代码,我认为您缺少基本网址。
应该像
axios.post(baseul + port + request url)
示例:
axios.post('http://localhost:3000/subscribe')