当调用同步获取以调用后端API时,响应仅包含从后端返回的部分数据。

huangapple go评论60阅读模式
英文:

When calling sync fetch to call backend api, response only contain part of the data that is returned from backend

问题

I am working on a course project. We are using JavaScript for frontend. When calling async fetch, the response only contains part of the data returned by backend.

For example, if backend api returns:

{
    "status": "success",
    "content": [
        {
            name: "ABC",
            key: "123456"
        }
    ]
}

The response that frontend receives:

{"status": "success"}

Here is my code:

Frontend:

export async function getObjectsFromS3(data) {
    const response = await fetch(url, {
        method: "GET",
        headers: {
            "Authorization": `Basic ${btoa("user:password")}`
        }
    });

    if (!response.ok) {
        throw an Error(response.status);
    }

    const result = await response.json();
    
    return result;
}

Backend:

@RestController
@RequestMapping("/users")
public class S3Controller {
    
    @Autowired
    S3Service s3Service;

    @GetMapping("/{userName}/objects")
    public String listObjects(@PathVariable String userName, @RequestParam String prefix) {
        AuthenticationUtil.authorizeUser(userName);
        String jsonString = "";
        JSONObject jo = new JSONObject();
        JSONArray ja = new JSONArray();

        ja.put("key");
        ja.put("name");
        ja.put("size");
        ja put("type");

        try {
            List<S3Object> objects = s3Service.listObjects(prefix);
            for (S3Object object : objects) {
                String suffix = object.key().replace(prefix, "");
                String[] suffixDir = suffix.split("/");

                if ((suffixDir.length == 1 && suffixDir[0] !== "")) {
                    String type, name, key;
                    key = object.key();

                    if (key.charAt(key.length() - 1) === '/')
                        type = "folder";
                    else
                        type = "file";

                    name = suffixDir[suffixDir.length - 1];

                    jsonString += object.key() + "," + name + "," + String.valueOf(object.size()) + "," + type + "\n";
                }
            }
            jo.put("status", "success");
            jo.put("content", CDL.toJSONArray(ja, jsonString));
        } catch (Exception e) {
            jo.put("status", "error");
            jo.put("message", "Error when listing files: " + e.getMessage());
        }

        return jo.toString();
    }

Here is the screenshot of DevTools' response. DevTool's Response

I have tried calling this API using Postman, and everything works. But when calling from the frontend, the response only contains part of the data.

英文:

I am working on a course project. We are using JavaScript for frontend. When calling async fetch, the response only contains part of the data returned by backend.

For example, if backend api returns:

{
    &quot;status&quot;: &quot;success&quot;,
    &quot;content&quot;: [
        {
            name: &quot;ABC&quot;,
            key: &quot;123456&quot;
        }
    ]
}

The reponse that frontend receives:

{&quot;status&quot;: &quot;success&quot;}

Here is my code:

Frontend:

export async function getObjectsFromS3(data) {
    const response = await fetch(url, {
        method: &quot;GET&quot;,
        headers: {
            &quot;Authorization&quot;: `Basic ${btoa(&quot;user:password&quot;)}`
        }
    });

    if (!response.ok) {
        throw new Error(response.status);
    }

    const result = await response.json();
    
    return result
}

Backend:

@RestController
@RequestMapping(&quot;/users&quot;)
public class S3Controller {
    
    @Autowired
    S3Service s3Service;

    @GetMapping(&quot;/{userName}/objects&quot;)
    public String listObjects(@PathVariable String userName, @RequestParam String prefix) {
        AuthenticationUtil.authorizeUser(userName);
        String jsonString = &quot;&quot;;
        JSONObject jo = new JSONObject();
        JSONArray ja = new JSONArray();

        ja.put(&quot;key&quot;);
        ja.put(&quot;name&quot;);
        ja.put(&quot;size&quot;);
        ja.put(&quot;type&quot;);

        try {
            List&lt;S3Object&gt; objects = s3Service.listObjects(prefix);
            for (S3Object object : objects) {
                String suffix = object.key().replace(prefix, &quot;&quot;);
                String[] suffixDir = suffix.split(&quot;/&quot;);

                if ((suffixDir.length == 1 &amp;&amp; suffixDir[0] !== &quot;&quot;)) {
                    String type, name, key;
                    key = object.key();

                    if (key.charAt(key.length() - 1) === &#39;/&#39;) 
                        type = &quot;folder&quot;;
                    else 
                        type = &quot;file&quot;;

                    name = suffixDir[suffixDir.length - 1];

                    jsonString += object.key() + &quot;,&quot; + name + &quot;,&quot; + String.valueOf(object.size()) + &quot;,&quot; + type + &quot;\n&quot;;
                }
            }
            jo.put(&quot;status&quot;, &quot;success&quot;);
            jo.put(&quot;content&quot;, CDL.toJSONArray(ja, jsonString));
        } catch (Exception e) {
            jo.put(&quot;status&quot;, &quot;error&quot;);
            jo.put(&quot;message&quot;, &quot;Error when listing files: &quot; + e.getMessage());
        }

        return jo.toString();
    }

Here is the screenshot of DevTools' response.
DevTool's Response

I have tried calling this api using postman, and everything works. But when calling from frontend, the reponse only contains part of the data.

答案1

得分: 0

1 删除后端服务器中的所有逻辑,只返回一个简单的JSON对象。

2 将数据放在一个名为 payload 的对象中,格式如下:

"payload": {
"status": "success",
"content": [
{
"name": "ABC",
"key": 123456
}
]
}
英文:

Two things worth to try:

1 Remove all your logics in backend server, just return a simple JSON object.

2 Put your data in one payload like this:

&quot;payload&quot;: {
&quot;status&quot;: &quot;success&quot;,
&quot;content&quot;: [
{
&quot;name&quot;: &quot;ABC&quot;,
&quot;key&quot;: 123456
}
]
}

huangapple
  • 本文由 发表于 2023年3月9日 15:27:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/75681544.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定