[英]request works with Postman but not with axios.post
我使用 axios.post() 在 React-js 中创建了一个注册表单。 该请求通过 Postman 完美运行,这使后端无罪,但在我的组件中没有任何反应。
使用 Try/catch 或 finally() 没有任何效果。 我在控制台中没有任何错误。 我所有的变量定义如下:
constructor(props) {
super(props);
this.state = {
passwd: ''
}
}
onFieldChange(fieldName) {
return function (event) {
this.setState({[fieldName]: event.target.value});
}
}
render() {
return (
[...]
<form onSubmit={() => this.handleSubmit()}>
<input type="password" value={this.state.passwd}
onChange={this.onFieldChange('passwd').bind(this)}
placeholder="* Password" required />
<button type="submit">Sign-up</button>
</form>
[...]
问题部分:((if/else)工作正常,重定向到 /SignIn 在其他地方工作)
handleSubmit(event) {
if (this.state.email === this.state.email02
&& this.state.passwd === this.state.passwd02
&& this.state.lastname !== '') {
const data = {
email: this.state.email,
passwd: this.state.passwd,
lastname: this.state.lastname,
firstname: this.state.firstname
}
const config = {
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}
axios.post('http://104.XX.YY.192:8081/register', data, config)
.then(response => {
this.props.history.push('/SignIn');
})
.catch(err => {
console.log(err);
})
} else if (this.state.email !== this.state.email02) {
console.log('email are not the same');
} else if (this.state.passwd !== this.state.passwd02) {
console.log('password are not the same');
}
}
我期待着您的回音。
我终于自己找到了解决方案。 'form' 标签在发送请求后重新加载页面。 将表单更改为 div 标签解决了我的问题。
由于您没有提供正确的错误日志,因此无法得到确切的问题。因此为您提供我的工作代码之一。它可能会有所帮助。 此代码片段获取 url,然后发布数据。在这里您可能会遇到 CORS 问题。 如果是,则在 package.json 中写入 -
“代理”:“ http://192.128.1.210:8080 ”
并安装 http-middleware-proxy。 它会正常工作:
export function PostData(userData) {
var targetUrl = '/report' /* /register in your case.*/
return new Promise((resolve, reject) => {
fetch(targetUrl, {
method: 'POST',
headers: {
'Content-Type': "application/json; charset=utf-8",
"Accept": "application/json"
},
body: JSON.stringify({
"requestData": {
"userName": userData.username,
"password": userData.password,
"clientId": "ptm",
"txnType": "GDR"
}
})
})
.then(response => response.json())
.then((responseJson) => {
resolve(responseJson)
})
.catch((error) => {
reject(error)
})
})
使用 axios one,这是您可以尝试的示例之一:
const user = {
name: this.state.name
};
axios.post(`https://jsonplaceholder.typicode.com/users`, {
user
})
.then(res => {
console.log(res);
console.log(res.data);
})
}
在设置标题时检查你的空格、逗号、引号,尤其是空格,而在 Postman 中你将它写在框中,但是当你在代码编辑器中进行硬编码时,有时拼写错误或添加了额外的空格 vs 这可能会导致错误
我有一个类似的问题,显然我的登录函数接受了 2 个字符串,但是我传递了一个包含 2 个字符串的 json 对象,我必须在 API 控制器中进行一些更改
创建了一个登录类
public class UserLogin
{
public string email { get; set; }
public string pass { get; set; }
}
并为 UserLogin 创建了一个对象作为参数,以便它可以接受用户 ID 和密码
public String Post(UserLogin ul){}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.