我正在使用 React 和 Express 開發節點 API。Node 像這樣從 Postgress 檢索資料:
router.get('/getRestaurants', async(req, res) => {
console.log('Restaurants');
try {
const { rows } = await db.getAllRestaurants();
console.log(rows);
res.json(rows);
} catch(error) {
console.error(`Error ${error}`);
res.status(500).send({message: `API internal error`});
}});
console.log 它顯示資料沒有問題,如果我使用 Postman 或 Curl,它似乎作業正常。但是當我嘗試從我的前端 React 中檢索資料時,我收到了這個錯誤:
Uncaught (in promise) SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data
React 發出這樣的 POST 請求:
useEffect(() => {
async function fetchData() {
const response = await fetch('http://172.20.0.4:3000/getRestaurants', {
method: 'GET', // *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': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
});
const data = await response.json();
console.log(data);
return data;
}
fetchData();
});
可能不難看出,但我缺少一些東西。先感謝您!
uj5u.com熱心網友回復:
我認為您對 CORS 有疑問,因為您要從另一個來源獲取資料,所以您需要 set mode: 'cors',這意味著您將跨來源獲取資料。當您將其設定為mode: 'no-cors'這意味著您不允許跨源時,這就是問題的原因。因為你說的。您的 express 應用與您的 react 應用具有不同的來源。但在您允許您的 express api(您從中獲取的來源)之前,它仍然無法作業。通過將標題設定為:ACCESS-CONTROLLE-ALLOW-ORIGIN *和星 * 表示允許所有型別的來源。但是如果你想允許一個特定的來源,用
*你的反應應用程式的 url 替換。您還可以使用 node.js 包,它會以一種干凈簡單的方式幫助您,例如使用 cors 包https://github.com/expressjs/cors:
const cors = require("cors");
let whitelist = ["http://localhost:3000"];
// Middleware
app.use(
cors({
origin: function (origin, callback) {
if (!origin) return callback(null, true);
if (whitelist.indexOf(origin) === -1) {
var message =
"The CORS policy for this origin doesnt "
"allow access from the particular origin.";
return callback(new Error(message), false);
}
return callback(null, true);
},
})
);
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/448443.html
