简体   繁体   中英

request works with Postman but not with axios.post

I created a registration form in React-js with axios.post(). The request works perfectly via Postman which makes the backend guilt-free, but don't have any reaction in my component.

Using Try/catch or finally() don't have any effect. i don't have any errors in the console. All my variables are defined as follows:

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

the problem part: (the (if/else) is working properly and redirection to /SignIn works elsewhere)

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');
    }
}

i'm looking forward to hearing from you.

I finally found the solution by myself. the 'form' tag reloads the page after sending the request. Changing the form to div tags solves my problem.

Since you have not given the proper Error Log so could not get the exact problem.Thus providing you one of my working code.It may help. This code snippet is taking the url and then posting the data.Here you may come across CORS issue. If yes, then in package.json write -

"proxy": " http://192.128.1.210:8080 "

and install http-middleware-proxy. It will work fine:

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)
      })
  })

With the axios one, this is one of the example you can try:

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 这可能会导致错误

I had a similar problem apparently my login function accepted 2 strings but I was passing a json object of 2 strings I had to make some changes in the API controller

Created a Login class

public class UserLogin
{
    public string email { get; set; }
    public string pass { get; set; }
}

and made an object for UserLogin as a parameter so that it can accept userID and Password

 public String Post(UserLogin ul){}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM