请求在Postman中有效,但在axios.post中无效。

huangapple go评论81阅读模式
英文:

request works with Postman but not with axios.post

问题

我在React-js中使用axios.post()创建了一个注册表单。
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="* 密码" required />
            <button type="submit">注册</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('电子邮件不相同');
        } else if (this.state.passwd !== this.state.passwd02) {
            console.log('密码不相同');
        }
    }

期待您的回复。

<details>
<summary>英文:</summary>

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&#39;t have any reaction in my component.

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

    constructor(props) {
        super(props);
        this.state = {
            passwd: &#39;&#39;
        }
    }
    
    onFieldChange(fieldName) {
        return function (event) {
            this.setState({[fieldName]: event.target.value});
        }
    }
    
    render() {
        return (
            [...]
            &lt;form onSubmit={() =&gt; this.handleSubmit()}&gt;
            &lt;input type=&quot;password&quot; value={this.state.passwd}
                   onChange={this.onFieldChange(&#39;passwd&#39;).bind(this)} 
                   placeholder=&quot;* Password&quot; required /&gt;
                &lt;button type=&quot;submit&quot;&gt;Sign-up&lt;/button&gt;
            &lt;/form&gt;
            [...]

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

    handleSubmit(event) {
        if (this.state.email === this.state.email02
            &amp;&amp; this.state.passwd === this.state.passwd02
            &amp;&amp; this.state.lastname !== &#39;&#39;) {
            const data = {
                email: this.state.email,
                passwd: this.state.passwd,
                lastname: this.state.lastname,
                firstname: this.state.firstname
            }
            const config = {
                headers: {&#39;Content-Type&#39;: &#39;application/x-www-form-urlencoded&#39;}
            }

            axios.post(&#39;http://104.XX.YY.192:8081/register&#39;, data, config)
                .then(response =&gt; {
                    this.props.history.push(&#39;/SignIn&#39;);
                })
                .catch(err =&gt; {
                    console.log(err);
                })
        } else if (this.state.email !== this.state.email02) {
            console.log(&#39;email are not the same&#39;);
        } else if (this.state.passwd !== this.state.passwd02) {
            console.log(&#39;password are not the same&#39;);
        }
    }

i&#39;m looking forward to hearing from you.


</details>


# 答案1
**得分**: 3

我终于自己找到了解决方案。
"form"标签在发送请求后重新加载页面。
将表单更改为div标签可以解决我的问题。

<details>
<summary>英文:</summary>

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



</details>



# 答案2
**得分**: 0

由于您没有提供适当的错误日志,因此无法确定确切的问题。因此,我提供一个有效的代码示例。这段代码片段接收一个URL,然后发送数据。在这里,您可能会遇到CORS问题。如果是的话,在package.json中写入以下内容:

```json
"proxy": "http://192.128.1.210:8080"

并安装http-middleware-proxy。它将正常工作:

export function PostData(userData) {
  var targetUrl = '/report' /* 在您的情况下是/register。 */
  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一起使用的话以下是一个示例

```javascript
const user = {
  name: this.state.name
};

axios.post(`https://jsonplaceholder.typicode.com/users`, {
    user
  })
  .then(res => {
    console.log(res);
    console.log(res.data);
  })
}

请注意,这只是示例代码,您需要根据您的实际需求进行适当的调整和配置。

英文:

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 = &#39;/report&#39; /* /register in your case.*/
  return new Promise((resolve, reject) =&gt; {
    fetch(targetUrl, {
        method: &#39;POST&#39;,
        headers: {
          &#39;Content-Type&#39;: &quot;application/json; charset=utf-8&quot;,
          &quot;Accept&quot;: &quot;application/json&quot;
        },
        body: JSON.stringify({
          &quot;requestData&quot;: {
            &quot;userName&quot;: userData.username,
            &quot;password&quot;: userData.password,
            &quot;clientId&quot;: &quot;ptm&quot;,
            &quot;txnType&quot;: &quot;GDR&quot;
          }
        })
      })
      .then(response =&gt; response.json())
      .then((responseJson) =&gt; {
        resolve(responseJson)
      })
      .catch((error) =&gt; {
        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 =&gt; {
    console.log(res);
    console.log(res.data);
  })
}

答案3

得分: 0

检查你的空格、逗号、引号,尤其是在设置标头时的空格,在Postman中你将其写在框中,但在代码编辑器中硬编码时,有时会拼写错误或多出空格,这可能会导致错误。

英文:

Check your spaces, commas, quotation marks, especially spaces when setting headers, while in Postman you write it in the boxes but when you hardcoding in the code editor, sometimes you misspelled or put extra space vs and this may cause errors

答案4

得分: 0

我遇到了一个类似的问题,显然我的登录函数接受了两个字符串,但我正在传递一个包含两个字符串的 JSON 对象,所以我不得不在 API 控制器中进行一些更改。

创建了一个名为 Login 的类

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

并将 UserLogin 对象作为参数,以便它可以接受用户ID和密码

public string Post(UserLogin ul) {}
英文:

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

huangapple
  • 本文由 发表于 2020年1月6日 18:01:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/59610044.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定