【发布时间】:2021-08-23 14:27:36
【问题描述】:
我有这个页面,它的作用是在表单提交时使用 axios 调用后端函数/updateServices。
import '../../../styles/services.css';
import axios from 'axios'
import React, { Component } from 'react';
class AddServicesPage extends Component {
constructor(props) {
super(props);
this.state = {
siteLocation: '',
Services: '',
date: '',
cnum: ''
};
}
handleInputChange = e => {
this.setState({
[e.target.name]: e.target.value,
});
};
handleSubmit = e => {
e.preventDefault();
var date = Date().toLocaleString()
const { siteLocation, Services, cnum } = this.state;
const selections = {
site: siteLocation,
content: Services,
updatedByCNUM: cnum,
};
axios
.post(`/updateServices`, selections)
.then(() =>
console.log("updating"),
window.location = "/admin/services"
)
.catch(function(error) {
// alert(error)
window.location = "/admin/services/new"
})
};
render() {
return (
<div className="App">
<div id="form-main">
<div id="form-div">
<form onSubmit={this.handleSubmit} className="form">
<select name="siteLocation" id="siteLocation" onChange={this.handleInputChange} >
<option value="OTT">Ottawa</option>
<option value="MAR">Markham</option>
</select>
<p className="email">
<input name="Services" type="text" className="validate[required,custom[email]] feedback-input" id="Services" placeholder="Services" onChange={this.handleInputChange} />
</p>
<p className="cnum">
<input name="cnum" type="text" className="validate[required,custom[email]] feedback-input" id="cnum" placeholder="cnum" onChange={this.handleInputChange} />
</p>
<div className="submit">
<input type="submit" value="SEND" id="button-blue"/>
<div className="ease"></div>
</div>
</form>
<a href="/tour">Get Results{'->'}</a>
</div>
</div>
</div>
);
}
}
export default AddServicesPage;
然而,它甚至没有击中表单提交的后端,而是跳过它并转到.then 说它正在工作。在后端,在我的/updateServices 中,它甚至不记录任何内容。它什么也不记录,甚至没有空行,这意味着它永远不会到达后端。我的代码有什么问题吗?
【问题讨论】:
-
您确定您的后端 API 端点 URL 设置正确吗?在上面的 sn-p 中,您只在 API 调用中调用
/updateServices,是否为 axios 配置了正确的 API 域?如果那是肯定的,那么我认为您必须检查您的后端路由,它可能会比您预期的更早被拦截并且只回复200 OK,另外作为一个附加提示,请考虑使用 React 路由器路由您的 React 应用程序,执行不要使用 window.location 因为它总是会刷新你的页面并且会丢失你的 React App 上下文。 -
你的前端和后端是否在同一个端口上运行?
-
@iunfixit 后端为 3001,前端为 3000
-
@HasinthaAbeykoon thx 4 提示。这很奇怪,因为它今天刚刚停止工作。从未遇到过这个问题,也没有更改代码。