2017-04-06 106 views
2

我想從數據庫中獲取用戶的信息,並顯示它,但我不斷收到此錯誤:Android的凌空:BasicNetwork.performRequest:意外的響應代碼404

BasicNetwork.performRequest: Unexpected response code 404

這裏是我的javacode:

裝方法:

public void loadUserProfile() { 

    Response.Listener<String> responseListener = new Response.Listener<String>() { 
     @Override 
     public void onResponse(String response) { 
      try { 
       JSONObject jsonResponse = new JSONObject(response); 
       idTV.setText(jsonResponse.getString("_id")); 
       nameTV.setText(jsonResponse.getString("name")); 
       firstNameTV.setText(jsonResponse.getString("firstName")); 
       emailTV.setText(jsonResponse.getString("email")); 
       sexTV.setText(jsonResponse.getString("sex")); 
       yearTV.setText(jsonResponse.getString("year")); 
       cursusTV.setText(jsonResponse.getString("cursus")); 
      } catch (JSONException e) { 
       onLoadProfileFail(); 
      } 
     } 
    }; 
    ProfileRequest profileRequest = new ProfileRequest(user_id, responseListener); 
    RequestQueue queue = Volley.newRequestQueue(ProfileActivity.this); 
    queue.add(profileRequest); 
} 

Request類

class ProfileRequest extends StringRequest { 
    private static final String USER_PROFILE_REQUEST = "http://[ipaddress]:8080/users/:id"; 
    private Map<String, String> params; 

    public ProfileRequest(String id, Response.Listener<String> listener) { 
     super(Method.POST, USER_PROFILE_REQUEST, listener, null); 
     params = new HashMap<>(); 
     params.put("id", id); 
    } 

    @Override 
    public Map<String, String> getParams() { 
     return params; 
    } 
} 

app.js

router.get('/users/:id', function(req, res) { 
    User.find({ _id: "ie00847" }, function(err, user) { 
     if (err) 
      res.send(err); 
     res.json(user); 
    }); 
}); 

回答

0

你得到了404錯誤,因爲你所訪問一個方法(POST)的路由不可用,因爲在app.js文件您的GET請求定義的函數,而而不是POST請求,因此您需要將Android代碼更新爲GET請求。像下面,

class ProfileRequest extends StringRequest { 
    private static final String USER_PROFILE_REQUEST = "http://[ipaddress]:8080/users"; 
    private Map<String, String> params; 

    public ProfileRequest(String id, Response.Listener<String> listener) { 
     super(Method.GET, USER_PROFILE_REQUEST + "/" + id, listener, null); 
    } 
} 

另外請注意,沒有必要重寫getParams()方法,你不發送POST請求了。另外,除了通過硬編碼URL中的值而不通過Map對象之外,您不能將參數添加到GET請求。

希望這會有所幫助:)

相關問題