![](/img/trans.png)
[英]NodeJs - fetch request from client always returns a 200 status response from the server regardless if there was an error updating the DB
[英]Simple get from soundcloud playlist works well in postmann. But Fetch returns status 200 yet no response
所以我使用 GET 方法和 Fetch 從 soundcloud 獲取一些數據。 在 postman 中,它工作正常。 但是當我使用 Fetch 時,我得到 Status:200 但是:“無法加載響應數據:沒有找到具有給定標識符的資源的數據”
const soundcloudUrl = 'https://api-v2.soundcloud.com/users/473442966/tracks?client_id=IPz5SBL08EN3FyBabMnvLpb0AAKYGtrd&limit=2&offset=0&linked_partitioning=1&app_version=1645088469&app_locale=en';
/**
* @param {string} url=''
* @param {string} method
*/
async function getData(url = '', method) {
console.log(url);
return fetch(url, {
method, // *GET, POST, PUT, DELETE, etc.
mode: 'no-cors', // no-cors, cors, *same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
// credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'text/plain',
// "Content-Type": "application/x-www-form-urlencoded",
},
redirect: 'follow', // manual, *follow, error
referrer: 'no-referrer', // no-referrer, *client
body: JSON.stringify(), // body data type must match "Content-Type" header
})
.then((response) => {
console.log(response.text());
return response.text();
})
.then((data) => {
console.log(data);
data ? JSON.parse(data) : {};
})
.catch((error) => {
console.log(error); // reject(error);
});
}
/**
* @param {object} data
*/
export async function getPodcaststreams(data) {
const url = new URL('', soundcloudUrl);
let response;
try {
response = await getData(url.href, 'GET');
} catch (e) {
return (e);
}
console.log(response);
}
這是我的網絡響應:網絡響應
這是我在 Postman 中得到的響應: postman 響應
另外,如果我點擊 url,我可以看到數據。
任何想法好人?
最好的祝福。
我可以看到你在這里做錯了兩件事。 首先是調用response.text()
兩次。 響應只能被讀取一次
console.log(response.text());
return response.text();
將無法讀取response
,因為它已被讀取。 這就是為什么您在嘗試解析數據時會收到未定義的響應。
其次,您無需調用JSON.parse(data)
,因為提取 api 包含一個response.json()
方法,該方法會將響應解析為 json。您的getData
應如下所示:
async function getData(url = '', method) {
return fetch(url, {
method,
mode: 'no-cors',
cache: 'no-cache',
headers: {
'Content-Type': 'text/plain'
},
redirect: 'follow',
referrer: 'no-referrer',
body: JSON.stringify()
})
.then((response) => {
return response.json();
})
.catch((error) => {
console.log(error); // reject(error);
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.