Windows 11 在适用于 Linux 的 Windows 子系统下运行 Ubuntu 22.04。 Postgresql 已安装在 Ubuntu 上并且正在运行。
我正在尝试使用 React 组件中的 axios 从数据库中读取表。
VITE正在使用中。
我的后端server.js代码如下:
const express = require('express');
const { Pool } = require('pg');
const app = express();
const port = 3000;
// PostgreSQL database configuration
const pool = new Pool({
user: 'admin',
host: 'localhost',
database: 'SRDB',
password: 'password',
port: 5432,
});
// Route handler for fetching products
app.get('/api/products', async (req, res) => {
try {
// Query products from the database
const { rows } = await pool.query('SELECT * FROM products');
console.log('Products:', rows);
// Send products data as JSON response
res.json(rows);
} catch (error) {
console.error('Error fetching products:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
});
app.get('/', (req, res) => {
res.send('Hello World!');
console.log('Hello World!');
});
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
axios 在这段代码中被调用:
import HeaderBar from "./HeaderBar.jsx";
import { useState, useEffect } from "react";
import { Outlet } from "react-router-dom";
import Footer from "./Footer.jsx";
import { CartProvider } from "./Context.jsx";
import { UserProvider } from "./Context.jsx";
import { ProductProvider } from "./Context.jsx";
import axios from "axios";
import Time from "./Time.jsx";
const AppLayout = () => {
const [UserData, setUserData] = useState(null);
const [ProductData, setProductData] = useState(["not ready yet"]);
useEffect(() => {
// Example: Fetch user data and product data
const fetchUserData = async () => {
// Replace the following with your actual API call or data loading logic
// const userData = await fetch("/api/user");
const userData = {
name: "John Doe",
email: "",
};
setUserData(userData);
};
const fetchProductData = async () => {
console.log(Time(), "Fetching product data...");
try {
const response = await axios.get("http://localhost:3000/api/products");
setProductData(response);
console.log(response);
} catch (error) {
// handle error
console.log("Error fetching product data:", error);
}
};
// Fetch data when the component mounts
fetchUserData();
fetchProductData();
}, []); // Empty dependency array means this effect runs once when the component mounts
return (
<>
<UserProvider value={{ UserData }}>
<ProductProvider value={{ ProductData }}>
<CartProvider>
<HeaderBar />
<Outlet />
<Footer className="footer" />
</CartProvider>
</ProductProvider>
</UserProvider>
</>
);
};
export default AppLayout;
从应用程序调用时,我在控制台中发现以下错误:
{stack: "AxiosError@http://lo…", message: "Network Error", name: "AxiosError", code: "ERR_NETWORK", config: Object, …}
config: {transitional: Object, adapter: Array(2), transformRequest: Array(1), transformResponse: Array(1), xsrfCookieName: "XSRF-TOKEN", …}
我已经在互联网上进行了一般搜索,也搜索了堆栈溢出。
我已经尝试了“http:”和“https:”的所有组合以及“localhost:”和“127.0.0.1:”前缀“3000/api/products”,但这些组合都不起作用。
我已核实:
const { rows } = await pool.query('SELECT * FROM products');
console.log('Products:', rows);
通过查看 console.log 正确地将数据从表返回到服务器
我发布解决方案代码,以防其他人遇到类似问题。
服务器.js:
const express = require('express');
const { Pool } = require('pg');
const cors = require('cors');
const app = express();
const port = 3000;
// Middleware for enabling CORS
app.use(cors());
// PostgreSQL database configuration
const pool = new Pool({
user: 'admin',
host: 'localhost',
database: 'SRDB',
password: 'password',
port: 5432,
});
// Route handler for fetching products
app.get('/api/products', async (req, res) => {
try {
// Query products from the database
const { rows } = await pool.query('SELECT * FROM products');
console.log('Products in server:', rows);
// Send products data as JSON response
res.json(rows);
} catch (error) {
console.error("Error fetching product data:", error.response?.data, error.toJSON())
res.status(500).json({ error: 'Internal Server Error' });
}
});
app.get('/', (req, res) => {
res.send('Hello World!');
console.log('Hello World!');
});
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
这是调用 Axios 的代码:
import HeaderBar from "./HeaderBar.jsx";
import { useState, useEffect } from "react";
import { Outlet } from "react-router-dom";
import Footer from "./Footer.jsx";
import { CartProvider } from "./Context.jsx";
import { UserProvider } from "./Context.jsx";
import { ProductProvider } from "./Context.jsx";
import axios from "axios";
import Time from "./Time.jsx";
const AppLayout = () => {
const [UserData, setUserData] = useState(null);
const [ProductData, setProductData] = useState(["not ready yet"]);
useEffect(() => {
// Example: Fetch user data and product data
const fetchUserData = async () => {
// Replace the following with your actual API call or data loading logic
// const userData = await fetch("/api/user");
const userData = {
name: "John Doe",
email: "",
};
setUserData(userData);
};
const fetchProductData = async () => {
try {
const response = await axios.get("http://localhost:3000/api/products");
setProductData(response.data);
} catch (error) {
// handle error
console.log("Error fetching product data:", error);
}
};
// Fetch data when the component mounts
fetchUserData();
fetchProductData();
}, []); // Empty dependency array means this effect runs once when the component mounts
return (
<>
<UserProvider value={{ UserData }}>
<ProductProvider value={{ ProductData }}>
<CartProvider>
<HeaderBar />
<Outlet />
<Footer className="footer" />
</CartProvider>
</ProductProvider>
</UserProvider>
</>
);
};
export default AppLayout;
为了完整起见,我添加了 vite.config.ts:
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import express from "express";
// Create an instance of Express
const app = express();
// Middleware to enable CORS
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader(
"Access-Control-Allow-Methods",
"GET, POST, OPTIONS, PUT, PATCH, DELETE"
);
res.setHeader("Access-Control-Allow-Headers", "*");
res.setHeader("Access-Control-Expose-Headers", "*");
res.setHeader("Access-Control-Allow-Credentials", "true");
res.setHeader("Access-Control-Max-Age", "86400");
next();
});
export default defineConfig({
plugins: [react()],
server: {
// Disable Vite's built-in middleware
// Provide a callback to hook into Vite's server start
configureServer: ({ middleware }) => {
// Attach the Express app to Vite's server middleware
middleware.use(app);
},
},
});
警告:如果遇到“错误:HTTP服务器不可用”的话,请从Vite服务器中删除middlewareMode属性。