[英]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.