What is wrong with this cod...
What is wrong with this cod...
To answer the interview question "What is wrong with this code for querying a native API?" let's analyze the provided code snippet and identify potential issues:
fetchToken() {
fetch('http://10.0.2.2:8163/extension/auth', {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-type': 'application/json'
}
})
.then((response) => console.log('successful fetchToken response: ', response.json()))
.catch((error) => console.log('fetchToken error: ', error))
.done();
}
Incorrect Handling of response.json()
:
response.json()
method returns a promise, but it is being logged directly without waiting for the promise to resolve. This will not log the actual JSON response but rather the promise object..then()
to handle the resolved JSON data.
fetchToken() {
fetch('http://10.0.2.2:8163/extension/auth', {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-type': 'application/json'
}
})
.then((response) => response.json())
.then((data) => console.log('successful fetchToken response: ', data))
.catch((error) => console.log('fetchToken error: ', error))
.done();
}
Error Handling:
Use of done()
:
.done()
method is not a standard part of the Fetch API or Promises in JavaScript. It is likely a mistake or a remnant from a different context (e.g., jQuery's Deferred objects)..done()
call.
fetchToken() {
fetch('http://10.0.2.2:8163/extension/auth', {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-type': 'application/json'
}
})
.then((response) => response.json())
.then((data) => console.log('successful fetchToken response: ', data))
.catch((error) => console.log('fetchToken error: ', error));
}
Network Configuration for Localhost:
localhost
does not refer to the development machine but to the device itself. The code correctly uses http://10.0.2.2:8163/
for Android emulators, which is an alias for 127.0.0.1
on the host machine.expert
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào