美文网首页我爱编程
axios在node中使用遇到的一个问题

axios在node中使用遇到的一个问题

作者: txwslyf | 来源:发表于2018-03-28 14:24 被阅读0次

node端代码如下:

var axios = require('axios')

axios.get('http://localhost/learnphp/?name=卢宇峰&age=22')
    .then(function (response) {
        console.log(response.data)
    })
    .catch(function (error) {
        console.log(error)
    })

后端采用的wamp,php代码如下:

<?php
header('Access-Control-Allow-Origin:*');       //解决浏览器跨域问题。
$res = array();
foreach ($_GET as $key => $value) {
    $res[$key] = $value;
}
echo json_encode($res);
?>

运行js脚本:

node request.js

会发现请求虽然成功了,但是看不到输出。
在网页端在尝试一下:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>

<body>


</body>
<script>
    axios.get('http://localhost/learnphp/?name=卢宇峰&age=22')
        .then(function (response) {
            console.log(response.data)
        })
        .catch(function (error) {
            console.log(error)
        })
</script>

</html>

输出结果如下:


image.png

可以看到拿到了预计中的结果。
那么究竟是什么导致了这个结果呢?看一下网页端发送的网络请求:


image.png
可以看到url其实需要被编码,而浏览器会帮我们自动编码。
知道了问题的原因,我们只要将node端的代码修改如下:
var axios = require('axios')

axios.get('http://localhost/learnphp/', {
        params: {
            name: '卢宇峰',
            age: 22,
        }
    })
    .then(function (response) {
        console.log(response.data)
    })
    .catch(function (error) {
        console.log(error)
    })

axios就会自动为我们进行url编码了。

相关文章

网友评论

    本文标题:axios在node中使用遇到的一个问题

    本文链接:https://www.haomeiwen.com/subject/uqwycftx.html