728x90
๋ฐ์ํ
๐ก next.js ํ๊ฒฝ ์ค์
npx create-next-app servertest
์ฐ๋ํ nextjs front๋ฅผ ํ๋ ๋ฏธ๋ฆฌ ๋ง๋ค์ด๋๋ค.
๐ด package ์ค์น (server ํด๋ ์๋ก์์ฑ)
//front nextjs ํด๋์ ๋ค๋ฅธ ๋
๋ฆฝ๋ ํด๋๋ฅผ ํ๋ ์์ฑํ
npm init -y
npm install express
npm install typescript @types/express
npm install tsnode @types/tsnode
๐ฃ index.ts ํ์ผ ์์ฑ
express ์๋ฒ๋ฅผ ์ค์ ํ๊ณ , ๊ตฌ์ฑํ๋ logic๋ฅผ ์์ฑํ๋ค.
import express, { Request, Response } from "express";
import cors from "cors";
const app = express();
app.use(cors());
// Define your Express routes, middleware, and other server configurations here
app.get("/api/data", (req: Request, res: Response) => {
// Handle your Express route logic here
res.json({ message: "Hello from Express server!" });
});
app.post("/api/click", (req: Request, res: Response) => {
// Handle your Express route logic here
res.send({ msg: "ํต์ ์๋ฃ!!" });
});
// Start the server
app.listen(5000, () => {
console.log("Express server is running on http://localhost:5000");
});
๐ฃ front code ์์
import Head from "next/head";
import Image from "next/image";
import { Inter } from "next/font/google";
import styles from "@/styles/Home.module.css";
// import fetch from "isomorphic-fetch";
// import getConfig from "next/config";
import { useEffect, useState } from "react";
// const { serverRuntimeConfig } = getConfig();
import axios from "axios";
const inter = Inter({ subsets: ["latin"] });
export default function Home() {
const [test, setTest] = useState();
const getData = async () => {
const result = await axios.get(`http://localhost:5000/api/data`);
console.log("์คํ");
console.log(result.msg);
};
const click = async () => {
const result = (await axios.post(`http://localhost:5000/api/click`)).data;
console.log(result);
setTest(result);
};
useEffect(() => {
// console.log("์คํ2", serverRuntimeConfig.expressServerUrl);
getData();
}, []);
return (
<>
<button
onClick={() => {
click();
}}
>
ํต์ ๋ฐ์๋ผ!
</button>
{test ? test : "ํต์ ์ "}
</>
);
}
๊ธฐ๋ณธ next.js ์์ฑ๋ front์์ ์์ ์ฝ๋๋ง ์ง์ฐ๊ณ , ์ฒ์ ์ ์ํ์๋ ํต์ ํ์ธํ๋ get ํต์ ๊ณผ, click ํ์ ๋์ ๋ฐ์์ ๋ณด๊ธฐ์ํ post ํต์ 2๊ฐ์ง๋ฅผ ์ค๋นํ๋ค.
๐ next.js ํ์ด์ง์์ express ์๋ฒ๋ฅผ ์ฌ์ฉ
์๋ฒ bash์์๋ ts-node index๋ฅผ ์ ๋ ฅํ๋ฉด ์๋ฒ๊ฐ ์ ์คํ๋๋ ๊ฒ์ ๋ณผ ์ ์๋ค.
front bash ์์๋ npm run dev๋ฅผ ์ ๋ ฅํ์ฌ next๋ฅผ ์คํํ๋ค.
๐ข ํ ์คํธ ๊ฒฐ๊ณผ
get ํต์ ์ด ์ฑ๊ณต์ ์ผ๋ก ์ด๋ฃจ์ด์ง๊ณ , message๋ฅผ return ๋ฐ์์์ ๋ณผ ์ ์๋ค.
๋ํ onclick ์ด ํด๋ฆญ์ ์ด๋ฏ๋ก ํต์ ์ ์ด ํ๊ธฐ๋๋ค.
ํด๋ฆญํ๊ณ , ์ํ๋ณํ๋ ์๋์ ๋์์์ ์๋ค.
๐ต
728x90
๋ฐ์ํ