JS fetch API GET方法两种实现差异解析:为何返回结果不同?
Hey there! Let’s break down what’s going on with your two GET requests—this is a super common gotcha when working with browser-based HTTP clients (I’m betting you’re using the fetch API here!).
为什么其中一个请求返回ƒ json() { [native code] }?
That output means you’re logging the raw Response object returned by your HTTP call, not the actual parsed data from the server. Here’s what that probably looks like in code:
// 错误示例:只拿到了Response对象,没解析内容 const faultyRequest = fetch('/your-api-endpoint'); console.log(faultyRequest); // 输出的是fetch返回的Promise/Response实例,其中包含原生的json()方法
The fetch API returns a Promise that resolves to a Response object. This object doesn’t hold your actual data directly—it has methods like json(), text(), and blob() to parse the raw response body into usable formats. When you log this object, you’re seeing the native json() method attached to it, not your task data.
为什么另一个请求能正常返回{tasks: Array(4)}?
This one’s working because you properly parsed the response body using the json() method. Here’s the correct pattern, either with .then() chaining:
// 正确示例:链式调用解析响应 fetch('/your-api-endpoint') .then(response => response.json()) // 调用json()解析,返回新的Promise .then(parsedData => { console.log(parsedData); // 这里就是你看到的{tasks: Array(4)} });
Or with async/await (which is cleaner for sequential code):
async function fetchTasks() { const response = await fetch('/your-api-endpoint'); const parsedData = await response.json(); // 关键的解析步骤! console.log(parsedData); } fetchTasks();
The response.json() method reads the response body, parses it as JSON, and returns another Promise that resolves to your actual task data. That’s why you’re seeing the array of tasks instead of a native method reference.
核心差异总结
- 无效请求: You only retrieved the raw
Responseobject (or didn’t wait for the Promise to resolve and parse the data), so you’re seeing the object’s built-injson()method instead of your data. - 有效请求: You followed up the initial HTTP call with
response.json()to parse the raw response body into the JSON data your server sent, then logged that parsed result.
内容的提问来源于stack exchange,提问作者artless boy

