React TypeScript를 Express TypeScript에 연결
35768 단어 typescriptjavascriptreacttutorial
이 튜토리얼의 범위 때문에 제 웹사이트 블로그를 링크하겠습니다. 더 나은 시각적 표현이 있습니다.
TypeScript로 React 및 Express.js 프로젝트 만들기 | 코딩PR
TypeScript Express.js 서버에서 간단한 TypeScript 반응 양식을 제공합니다.
codingpr.com
1. 노드 환경을 설정합니다.
Terminal
mkdir simple-react-form
cd simple-react-form
Terminal
npm init -y
code .
2. Express.js 및 TypeScript를 설정합니다.
Install through npm or yarn
npm install cors dotenv express
npm install -D typescript @types/cors @types/express @types/node concurrently nodemon
Config
npx tsc --init
tsconfig.json
{
"compilerOptions": {
"target": "es2016",
"jsx": "preserve",
"module": "commonjs",
"allowJs": true,
"outDir": "./dist",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true
},
"exclude": [
"client",
"dist",
"node_modules"
]
}
package.json
{
"scripts": {
"build": "npx tsc",
"start": "node dist/index.js",
"dev": "concurrently \"npx tsc --watch\" \"nodemon -q dist/index.js\"",
"test": "echo \"Error: no test specified\" && exit 1"
},
}
index.ts
import dotenv from "dotenv";
import express, { Express, Request, Response } from "express";
import path from "path";
import cors from "cors";
dotenv.config();
const app: Express = express();
app.use(express.json());
app.use(cors());
app.get('/', (req: Request, res: Response) => {
res.send('<h1>Hello World From the Typescript Server!</h1>')
});
const port = process.env.PORT || 8000;
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
});
Terminal
npm run build
npm run dev
3. React 및 TypeScript를 설정합니다.
Terminal
npx create-react-app client --template typescript
Git Bash
$ cd client
$ rm -rf .git
Git Bash
$ cd src
$ mkdir components
$ mkdir utils
Git Bash
$ cd components
$ mkdir form-input
$ cd form-input
$ touch form-input.tsx
client/src/components/form-input/form-input.tsx
import { InputHTMLAttributes, FC } from "react";
import './form-input.css';
type FromInputProps = { label: string } &
InputHTMLAttributes<HTMLInputElement>;
const FormInput: FC<FromInputProps> = ({ label, ...otherProps }) => {
return (
<div className="group">
<input {...otherProps} />
{
label &&
<div className="form-input-label">
{label}
</div>
}
</div>
);
}
export default FormInput;
client/src/utils/data-utils.ts
export const getData = async <T>(
url: string,
email: string,
password: string
)
: Promise<T> => {
const res = await fetch(url, {
method: 'Post',
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify({ email, password })
});
return await res.json();
}
client/src/App.tsx
import { useState, ChangeEvent, FormEvent } from "react";
import { ReactComponent as Logo } from "./logo.svg";
import { getData } from "./utils/data-utils";
import FormInput from './components/form-input/form-input';
import './App.css';
// TypeScript declarations
type User = {
id: number,
name: string,
email: string,
password: string
}
const defaultFormFields = {
email: '',
password: '',
}
const App = () => {
// react hooks
const [user, setUser] = useState<User | null>()
const [formFields, setFormFields] = useState(defaultFormFields)
const { email, password } = formFields
const resetFormFields = () => {
return (
setFormFields(defaultFormFields)
);
}
// handle input changes
const handleChange = (event: ChangeEvent<HTMLInputElement>) => {
const { name, value } = event.target
setFormFields({...formFields, [name]: value })
}
const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
event.preventDefault()
try {
// make the API call
const res:User = await getData(
'http://localhost:8000/login', email, password
)
setUser(res);
resetFormFields()
} catch (error) {
alert('User Sign In Failed');
}
};
const reload = () => {
setUser(null);
resetFormFields()
};
return (
<div className='App-header'>
<h1>
{ user && `Welcome! ${user.name}`}
</h1>
<div className="card">
<Logo className="logo" />
<h2>Sign In</h2>
<form onSubmit={handleSubmit}>
<FormInput
label="Email"
type="email"
required
name="email"
value={email}
onChange={handleChange}
/>
<FormInput
label="Password"
type='password'
required
name='password'
value={password}
onChange={handleChange}
/>
<div className="button-group">
<button type="submit">Sign In</button>
<span>
<button type="button" onClick={reload}>Clear</button>
</span>
</div>
</form>
</div>
</div>
);
}
export default App;
4. 새 경로와 TypeScript를 서버에 추가합니다.
index.ts
interface FormInputs {
email: string,
password: string
}
// Array of example users for testing purposes
const users = [
{
id: 1,
name: 'Maria Doe',
email: '[email protected]',
password: 'maria123'
},
{
id: 2,
name: 'Juan Doe',
email: '[email protected]',
password: 'juan123'
}
];
// route login
app.post('/login', (req: Request, res: Response) => {
const { email, password }:FormInputs = req.body;
const user = users.find(user => {
return user.email === email && user.password === password
});
if (!user) {
return res.status(404).send('User Not Found!')
}
return res.status(200).json(user)
});
Terminal
npm run dev
cd client
npm start
Reference
이 문제에 관하여(React TypeScript를 Express TypeScript에 연결), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/denisseab/connect-react-typescript-to-express-typescript-57b8텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)