简体   繁体   English

服务器是否应该始终将JSON对象作为http响应发送?

[英]Should a server always send a JSON object as an http response?

I'm working on a node.js server using express and a android native app, using Retrofit 1.9. 我正在使用express和一个Android本机应用程序(使用Retrofit 1.9)在node.js服务器上工作。 For a login API that returns only a true/false answer to the client, should JSON still be used? 对于仅返回客户端正确/错误答案的登录API,是否仍应使用JSON?

As I see it, the server has only to send a status code response: 如我所见,服务器只需发送一个状态码响应:

if(isLegal) {
    res.sendStatus(200);
    dbConnector.updateUser(token);
}
else{
    console.log('Token is not legal');
    res.sendStatus(403);
}

But the Retrofit framework tries to convert the response to JSON, which makes me think I must send a JSON object with the answer, though it seems weird. 但是Retrofit框架尝试将响应转换为JSON,这使我认为我必须发送带有答案的JSON对象,尽管看起来很奇怪。

My retrofit restClient: 我的改造restClient:

public class RestClient {
private static final String URL = SessionDetails.getInstance().serverAddress;

private retrofit.RestAdapter restAdapter;
private ServerAPI serverAPI;

public RestClient() {

    restAdapter = new retrofit.RestAdapter.Builder()
            .setEndpoint(URL)
            .setLogLevel(retrofit.RestAdapter.LogLevel.FULL)
            .build();

    serverAPI = restAdapter.create(ServerAPI.class);
}

public ServerAPI getService() {
    return serverAPI;
}

} }

And usage: 和用法:

            restClient.getService().login(token.getToken(), token.getUserId(), new Callback<Void>() {
            @Override
            public void success(Void aVoid, Response response) {
                Log.d("Chooser", "Successful login on server.");
            }

            @Override
            public void failure(RetrofitError error) {
                error.printStackTrace();
                Log.d("Chooser", "Login failed on server.");
            }
        });

Using it as it is results with the following error: 按原样使用它会导致以下错误:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING com.google.gson.JsonSyntaxException:java.lang.IllegalStateException:预期为BEGIN_OBJECT,但为STRING

There are many topics on this issue but no certain answer about the correct (or better) method to use. 关于此问题有很多主题,但是对于要使用的正确(或更好)方法没有确定的答案。

Any ideas about the best implementation in these cases? 在这些情况下,关于最佳实施的任何想法?

Sending an empty body with your HTTP response is perfectly legal and some clients may care only about the response status but some clients may expect to get a response so sending a body never hurts and sometimes may be useful. 使用HTTP响应发送空的正文是完全合法的,有些客户端可能只关心响应状态,但是有些客户端可能希望得到响应,因此发送正文永远不会造成伤害,有时可能有用。

You can include a JSON response in addition to the HTTP response status: 除了HTTP响应状态之外,还可以包括JSON响应:

// Express 4.x:
res.status(403).json({error: 'Token is not legal'});

// Express 3.x:
res.json(403, {error: 'Token is not legal'});

Such an error message can be very useful for the client development. 这样的错误消息对于客户端开发可能非常有用。 You can get 403 for many reasons, illegal token, expired token, a legal not expired token but for the wrong user that doesn't have some privilege - adding a specific error message in addition to the HTTP response code can tell the client what exactly went wrong and allows the client-side code to show a better error message to the user. 出于多种原因,您可以获得403,包括非法令牌,过期令牌,合法未过期令牌,但对于没有特权的错误用户-除了HTTP响应代码外,添加特定错误消息还可以告诉客户端确切的内容出错,并允许客户端代码向用户显示更好的错误消息。

Also, note that true and false are also valid JSON. 另外,请注意, truefalse也是有效的JSON。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM