【发布时间】:2019-11-28 17:49:14
【问题描述】:
我刚刚进入 Next.js,但我不知道如何将我的 next.js 应用程序与我的 express api 连接起来。我能够让它工作,但我很确定这不是实现它的正确方法,因为在我的 Index 组件中我硬编码了 fetch url,我知道在生产中如果端口不同它不会工作。
我试图只放置路由,而 fetch API 不允许这样做。
我的索引页面是这样的
import Link from "next/link";
import fetch from "isomorphic-unfetch";
const Index = props => (
<>
<h1>Youtubers</h1>
<ul>
{props.youtubers.map(youtuber => (
<li key={youtuber._id}>
<Link as={`/p/${youtuber._id}`} href={`/post?id=${youtuber.id}`}>
<a>{youtuber.name}</a>
</Link>
</li>
))}
</ul>
</>
);
Index.getInitialProps = async function() {
// this url I think is wrong ↓
const res = await fetch("https://localhost:5000/youtuber");
const data = await res.json();
return {
youtubers: data.youtubers
};
};
export default Index;
在我的 server.js 中,我在 app.prepare().then() 中有这个
server.use(bodyParser.urlencoded({ extended: false }));
server.use(bodyParser.json());
mongoose.connect(process.env.MONGODB_PASSWORD, {
useNewUrlParser: true,
useCreateIndex: true
});
mongoose.connection.on("open", function() {
console.log("mongodb is connected!!");
});
mongoose.connection.on(
"error",
console.error.bind(console, "MongoDB connection error:")
);
//CORS handler
server.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept, Authorization"
);
if (req.method === "OPTIONS") {
res.header(
"Access-Control-Allow-Methods",
"PUT, POST, PATCH, DELETE, GET"
);
return res.status(200).json({});
}
next();
});
//Question Route
server.use("/youtuber", youtuberRoutes);
server.get("*", (req, res) => {
return handle(req, res);
});
server.listen(port, err => {
if (err) throw err;
console.log(`> Ready on http://localhost:${port}`);
});
【问题讨论】:
-
您的
fetch似乎正在使用https,但我没有看到您的 Express 应用程序中设置了https。如果不了解youtuberRoutes是如何定义的,就无法查看您匹配的 URL 是否会匹配任何路由。
标签: node.js reactjs mongodb express next.js