JSON 数据的第 1 行第 1 列的数据意外结束,用 React 表达

unexpected end of data at line 1 column 1 of the JSON data in express with React

我正在使用 React 和 Express 在节点 API 上工作。节点像这样从 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();
});

可能不难看出,但我遗漏了一些东西。提前致谢!

我认为你的 CORS 有问题,因为你从另一个来源获取数据,你需要设置 mode: 'cors',这意味着你将跨来源获取数据。当您将它设置为 mode: 'no-cors' 时,这意味着您不允许交叉来源,这就是问题的原因。因为你说的。您的 Express 应用程序与您的 React 应用程序的来源不同。但它仍然无法工作,直到您允许您的快递 api,您正在获取的来源。通过将 headers 设置为:ACCESS-CONTROLLE-ALLOW-ORIGIN * 并且星号 * 表示允许所有类型的来源。但如果你想允许一个特定的来源,更换 * 与 url 你的 React 应用。你也可以使用一个 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);
        },
    })
);