json之使用API时Vue不返回数据

linjiqin 阅读:207 2025-06-02 22:19:02 评论:0

我创建了自己的后端api,当我在chrome上测试api时,它可以正常工作,但是当我使用axios使用api时,它不返回任何数据。我正在使用vue。

axios.get('http://192.168.149.12:8888/api/user/5120') 
            .then(res => { 
                this.data = res;  
            })  
            .catch(err => { 
                this.data = err; 
            }); 

响应:
{ "data": "", "status": 200, "statusText": "OK", "headers": { "content-length": "0" }, "config": { "url": "http://192.168.149.12:8888/api/user/5120", "method": "get", "headers": { "Accept": "application/json, text/plain, */*" }, "transformRequest": [ null ], "transformResponse": [ null ], "timeout": 0, "xsrfCookieName": "XSRF-TOKEN", "xsrfHeaderName": "X-XSRF-TOKEN", "maxContentLength": -1 }, "request": {} } 

如您所见,数据为空,但是当我尝试使用一些 public api(例如JSONPlaceholder)时,它可以正常工作。

这是我的json API的格式:
{ 
"user": { 
  "example": false, 
  "example1": "/zTxHf9iIOCqRbxvl8W5QYKrsMLq.jpg" 
 } 
} 

编辑(我发现了问题)

每当用户发出API请求时,我都会检查 session 是否有效
userCookie, err := r.Cookie("session-id") 
    if err != nil { 
        fmt.Println(err) 
        if strings.HasPrefix(r.URL.Path, "/login") { 
            Login(w, r, db) //login and create session 
        } 
   } else { 
     //Authenticate Session Then if Valid proceed to my APIs 
   } 

因此,当我直接在浏览器的搜索栏上使用API​​时,它可以工作,因为它检测到了session(cookie),但是当我在Vue / axios上使用它时,它却没有检测到Cookie,并且出现了以下错误:
http: named cookie not present 
exit status 1 

创建 session 时,我将cookie设置为 Path: "/",因此即使服务器和前端具有不同的端口, session cookie也会生成到我的Vue页面。 那么,如何使服务器在Vue页面上检测到 session cookie?

请您参考如下方法:

我怀疑问题可能出在您的API上。

Postman / Postwoman / Insomnia上测试API以查看响应。
如果API在API测试工具上返回了数据,则当在axios上使用时,它应该可以正常运行。

请参见以下示例:



var app = new Vue({ 
       el: '#app', 
 
       data: { 
        response: '', 
       },      
  
       methods:{ 
        runApi:function(){ 
            axios.get('https://jsonplaceholder.typicode.com/todos/1').then(response=>{ 
                this.response = response.data; 
                console.log(this.response); 
                 
            }).catch(function(error){ 
                console.log('error : ',error); 
            })   
        } 
       }, 
 
       mounted:function(){ 
           this.runApi();         
        } 
    })
<script src="https://unpkg.com/axios/dist/axios.min.js"></script> 
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> 
 
 
<div id="app"> 
<p> 
{{ response }} 
</p> 
</div>


标签:VUE
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号