npm run dev
和
node server/server.js
,但是在使用服务器作为NetLify函数的问题上运行良好vite.config.js代理设置
netlify dev
netlify.toml
server: {
// port: 3000,
proxy: {
"/api": {
target: "http://localhost:5022",
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, ""),
secure: false,
},
},
},
netlify/functions/api.mjs
[build]
command = "npm run build"
publish = "dist"
functions = "functions"
[[redirects]]
from = "/*"
to = "/index.html"
status = 200
[[redirects]]
from = "/api/*"
to = "/.netlify/functions/:splat"
status = 200
import { config } from "dotenv";
import express from "express";
config();
const api = express();
api.use(express.json());
...
api.get("/hello", (req, res) => res.send("Hello from api.mjs!"));
app.listen(process.env.PORT || 5022, () => {
console.log(`Server listening on port ${process.env.PORT || 5022}`);
});
Error建议代理服务器不运行
useEffect(() => {
const callHello = async () => {
try {
const response = await axios.get('/api/hello');
console.log("Response:", response.data);
} catch (error) {
console.error("Error:", error);
}
};
callHello();
},[])
我有多个错误。
the vite.config.js代理NETLIFY.TOML和
Server.js
8:57:13 AM [vite] http proxy error: /hello
AggregateError [ECONNREFUSED]:
at internalConnectMultiple (node:net:1128:18)
at afterConnectMultiple (node:net:1693:7)
import express, { Router } from "express";
import serverless from "serverless-http";
const api = express();
const router = Router();
router.get("/hello", (req, res) => res.send("Hello World!"));
api.use("/api/", router);
export const handler = serverless(api);
npm run dev
node netlify/functions/api.mjs
继续,netlify.toml需求express和esbuild
// export const handler = serverless(api);
const port = process.env.PORT || 8888;
api.listen(port, () => {
console.log(`Local server listening on port ${port}`);
});
你确定是[functions]
external_node_modules = ["express"]
node_bundler = "esbuild"
[build]
command = "npm run build"
publish = "dist"
[[redirects]]
force = true
from = "/api/*"
to = "/.netlify/functions/api/:splat"
status = 200
[[redirects]]
from = "/*"
to = "/index.html"
status = 200
吗? 是的! 查看NetLify的GET始于函数:Routerequests 但仍未运行。 真是个阻力!
端口需要为8888,即NetLify Dev正在运行:
to = "/.netlify/functions..."
。太好了!
如果您运行
Netlify Dev: Serving your site on http://localhost:8888
现在,它将崩溃。
vite.config正在重写API路径,需要删除!
因此,vite.config.js代理的最终版本就是这样。
netlify dev
server: {
proxy: {
"/api": {
target: env.VITE_API_URL || "http://localhost:8888",
changeOrigin: true,
},
},
},
。 请记住,如果您正在运行它们,请关闭Vite和节点服务器。
netlify dev