【问题标题】:ReactJS AXIOS post doesn't workReactJS AXIOS 帖子不起作用
【发布时间】:2018-03-01 02:05:44
【问题描述】:

我正在尝试向 API 提交登录表单,但是该 API 未通过发布请求测试。

ReactJS 动作:

/**
 * Sends login request to API
 */
export function login(email, password) {
    console.log('Credentials:', email, password)
    const request = axios.post(`${ROOT_URL}login/login`, 
        {
            email,
            password
        })
        .then((response) => console.log(response))
        .catch((error) => console.log(error));
}

从 api 登录功能:

    public function actionLogin($credentials = [])
    {
        $request = Yii::$app->request;

        if ($request->post()) { 
            // handle the user login
        } else {
            return Json::encode(['status' => false, 'data' => 'error_no_request']);
        }
    }

控制台记录响应 - 很明显它没有通过请求测试。

标题:

Response Headers
Access-Control-Allow-Origin:*
Connection:Keep-Alive
Content-Length:42
Content-Type:text/html; charset=UTF-8
Date:Wed, 20 Sep 2017 06:42:06 GMT
Keep-Alive:timeout=5, max=98
Server:Apache/2.4.18 (Win32) OpenSSL/1.0.2e PHP/7.0.8
X-Powered-By:PHP/7.0.8

Request Headers
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:56
Content-Type:application/json;charset=UTF-8
Host:127.0.0.1
Origin:http://localhost:8080
Referer:http://localhost:8080/login

控制台记录请求。

【问题讨论】:

  • 如果the API doesn't receive the request 那是什么照片?确实看起来像一个响应状态为 200 的 XMLHttpRequest
  • 说错了。它接收到请求,但没有进入登录处理部分。

标签: javascript php reactjs yii2 axios


【解决方案1】:

好的,既然 POST 方法不起作用,我用 GET 方法尝试了它。由于某种原因,它有效。动作现在看起来像:

export function login(email, password) {
    const request = axios({
        headers: { 
            'content-type': 'application/json'
        },
        method: 'post',
        url: `${ROOT_URL}login/login`,
        params: {
            email,
            password
        }
    })
    .then((response) => response.data)
    .catch((error) => error);
}

【讨论】:

    【解决方案2】:

    您将正文数据作为 null 传递。

    编辑:

    const request = axios.post(`${ROOT_URL}login/login`, 
        {
            email,
            password
        })
        .then((response) => console.log(response))
        .catch((error) => console.log(error));
    

    收件人:

    const request = axios.post(`${ROOT_URL}login/login`, 
        data:{
            email,
            password
        })
        .then((response) => console.log(response))
        .catch((error) => console.log(error));
    

    Body 需要 data 关键字作为 axios post 请求附加 json 对象的主体数据。 检查documentation

    【讨论】:

    • 还是不行。检查了文档并以两种方式工作
    • 您的网络标签显示您发送的数据是什么?
    • @MoldovanAndrei 还将标题内容类型设置为 application/json 而不是 text/html
    • 它们已经设置为 application/json。编辑了问题,以便您可以看到它们。
    • 你能显示 API 被命中时 $request 打印的内容吗?
    猜你喜欢
    • 1970-01-01
    • 2019-01-26
    • 2021-08-14
    • 2021-09-10
    • 2019-07-11
    • 2020-02-29
    • 2018-12-15
    • 2018-12-04
    • 1970-01-01
    相关资源
    最近更新 更多