173만명의 커뮤니티!! 함께 토론해봐요.
해결됨
[코드캠프] 부트캠프에서 만든 고농축 프론트엔드 코스
포토폴리오 마이페이지 - 내포인트 부분을 작업하는 도중 api 질문입니다. fetchPointTransactionsOfBuying 이 내포인트 -> 구매내역 api로 알고있습니다. 피그마를 보면 거기서 판매자 데이터를 가져오고있는데 오류가 뜨네요.ㅠ 판매자 데이터를 가져오고 싶은데 여기서 seller {name} 이부분을 넣으면 데이터가 안가져오네요.. 판매자데이터가 없어서 그런건지 왜 그런지와 어떻게 해야하는지 두가지 모두 알고싶습니다.
react node.js seo graphql next.js
임프런
2023-07-12T01:24:53.686Z
댓글 2
좋아요 0
조회수 381
미해결
Slack 클론 코딩[실시간 채팅 with React]
안녕하세요. 강의 잘 듣고 있습니다. 다름이 아니라 login 한 후 workspace로 리다이렉트 된 후, workspace 목록이 아래와 같이 나타나지 않는 현상이 발생합니다. 하지만 다른 탭을 다녀오거나, workspace 추가를 하면 다시 정상적으로 아래와 같이 workspace 목록이 나타납니다. 아마 userData를 리다이렉트하면서 불러오지 않아 생기는 문제 같습니다. mutate()를 사용하고, dedupinginterval을 줄여도 문제 해결이 안되는 것 같아 리다이렉트됨과 동시에 다시 userData를 불러오도록 수정해야 할 것 같은데, 이를 구현할 수 있는 방법이 생각이 나지 않습니다. 현재 제 코드 일부 아래에 첨부합니다. App.js const App: FC = () => { return ( <Switch> <Redirect exact path="/" to="/login" /> <Route path="/login" component={LogIn} /> <Route path="/signup" component={SignUp} /> <Route path="/workspace/:workspace" component={Workspace} /> </Switch> ); }; Login/index.tsx const LogIn = () => { const {data, error, mutate} = useSWR('/api/users', fetcher, { dedupingInterval: 100000, }); const [logInError, setLogInError] = useState(false); const [email, onChangeEmail] = useInput(''); const [password, onChangePassword] = useInput(''); const onSubmit = useCallback( (e) => { e.preventDefault(); setLogInError(false); axios .post( '/api/users/login', { email, password }, { withCredentials: true }, ) .then((response) => { mutate(response.data, false); //Optimistic UI }) .catch((error) => { setLogInError(error.response?.status === 401); }); }, [email, password], ); if (data === undefined) { return <div>로딩중...</div>; } if (data) { return <Redirect to="/workspace/sleact/channel/일반" />; } Workspace/index.tsx import Menu from "@components/Menu"; import Modal from "@components/Modal"; import CreateChannelModal from "@components/CreateChannelModal"; import useInput from "@hooks/useinput"; import fetcher from "@utils/fetcher"; import axios from "axios"; import React, { FunctionComponent, useCallback, useState } from "react" import { Link, Redirect, Route, Switch, useParams } from 'react-router-dom'; import { toast } from 'react-toastify'; import useSWR from "swr"; import { AddButton, Channels, Chats, Header, LogOutButton, MenuScroll, ProfileImg, ProfileModal, RightMenu, WorkspaceButton, WorkspaceModal, WorkspaceName, WorkspaceWrapper, Workspaces } from "@layouts/Workspace/style"; import gravatar from 'gravatar'; import { Button, Input, Label } from '@pages/SignUp/style'; import { IChannel, IUser } from "@typings/db"; import loadable from "@loadable/component"; const Channel = loadable(() => import('@pages/SignUp')); const DirectMessage = loadable(() => import('@layouts/Workspace')); const Workspace: FunctionComponent = () => { const [showUserMenu, setShowUserMenu] = useState(false); const [showCreateWorkspaceModal, setShowCreateWorkspaceModal] = useState(false); const [showWorkspaceModal, setShowWorkspaceModal] = useState(false); const [showCreateChannelModal, setShowCreateChannelModal] = useState(false); const [newWorkspace,onChangeNewWorkspace, setNewWorkSpace] = useInput(''); const [newUrl, onChangeNewUrl, setNewUrl] = useInput(''); const { workspace } = useParams<{workspace: string}>(); const { data: userData , error, mutate} = useSWR<IUser | false>( '/api/users', fetcher, { dedupingInterval: 2000, } ); const { data: channelData } = useSWR<IChannel[]>( userData? `api/workspaces/${workspace}/channels` : null, fetcher ); const onLogout = useCallback(() => { axios .post('/api/users/logout', null, { withCredentials: true, }) .then(() => { mutate(false, false); }); }, []) const onClickUserProfile = useCallback((e) => { e.stopPropagation(); setShowUserMenu((prev) => !prev); }, []); const onClickCreateWorkSpace = useCallback(() => { setShowCreateWorkspaceModal(true); }, []); const onCreateWorkspace = useCallback((e) => { e.preventDefault(); if(!newWorkspace || !newWorkspace.trim()) return; if(!newUrl || !newUrl.trim()) return; axios .post( '/api/workspaces', { workspace: newWorkspace, url : newUrl, }, { withCredentials: true, }) .then(() => { mutate(); setShowCreateWorkspaceModal(false); setNewWorkSpace(''); setNewUrl(''); }) .catch((error)=>{ console.dir(error); toast.error(error.response?.data, { position: 'bottom-center' }); }); }, [newWorkspace, newUrl]); const onCloseModal = useCallback(() => { setShowCreateWorkspaceModal(false); setShowCreateChannelModal(false); }, []); if(!userData) { return <Redirect to="/login"/> } const toggleWorkspaceModal = useCallback(()=> { setShowWorkspaceModal((prev) => !(prev)); },[]); const onClickAddChannel = useCallback(() => { setShowCreateChannelModal(true); }, []); return ( <div> <Header> <RightMenu> <span onClick = {onClickUserProfile}> <ProfileImg src = {gravatar.url(userData.email, {s: '28px', d: 'retro'})} alt= {userData.nickname}/> {showUserMenu && ( <Menu style={{right:0, top:38}} show={showUserMenu} onCloseModal={onClickUserProfile}> <ProfileModal> <img src={gravatar.url(userData.email, {s: '36px', d: 'retro'})} alt= {userData.nickname}/> <div> <span id="profile-name">{userData.nickname}</span> <span id="profile-active">Active</span> </div> </ProfileModal> <LogOutButton onClick={onLogout}>로그아웃</LogOutButton> </Menu> )} </span> </RightMenu> </Header> <WorkspaceWrapper> <Workspaces> {userData?.Workspaces?.map((ws) => { return ( <Link key={ws.id} to={'/workspace/${123}/channel/일반'}> <WorkspaceButton>{ws.name.slice(0,1).toUpperCase()}</WorkspaceButton> </Link> ); })} <AddButton onClick={onClickCreateWorkSpace}>+</AddButton> </Workspaces> <Channels> <WorkspaceName onClick={toggleWorkspaceModal}> Sleact </WorkspaceName> <MenuScroll> <Menu show={showWorkspaceModal} onCloseModal={toggleWorkspaceModal} style={{ top: 95, left: 80}}> <WorkspaceModal> <h2>Sleact</h2> <button onClick={onClickAddChannel}>채널 만들기</button> <button onClick={onLogout}>로그아웃</button> </WorkspaceModal> </Menu> {channelData?.map((v) => (<div>{v.name}</div>))} </MenuScroll> </Channels> <Chats> <Switch> <Route path="/workspace/:workspace/channel/:channel" component={Channel} /> <Route path="/workspace/:workspace/dm/:id" component={DirectMessage} /> </Switch> </Chats> </WorkspaceWrapper> <Modal show={showCreateWorkspaceModal} onCloseModal={onCloseModal}> <form onSubmit={onCreateWorkspace}> <Label id="workspace-label"> <span>워크스페이스 이름</span> <Input id="workspace" value={newWorkspace} onChange={onChangeNewWorkspace}/> </Label> <Label id="workspace-url-label"> <span>워크스페이스 url</span> <Input id="workspace-url" value={newUrl} onChange={onChangeNewUrl}/> </Label> <Button type="submit">생성하기</Button> </form> </Modal> <CreateChannelModal show={showCreateChannelModal} onCloseModal={onCloseModal} setShowCreateChannelModal={setShowCreateChannelModal} /> </div> ) } export default Workspace
react 웹팩 typescript socket.io babel 클론코딩
김호준
2023-07-10T16:29:35.565Z
댓글 1
좋아요 0
조회수 733
해결됨
처음 만난 리액트(React)
jsx강의 에서는 jsx는 내부적으로 html/xml코드를 자바스크립트로 변환하는 과정 을 거치게 된다. 그래서 최종적으로는 자바스크립트 코드로 나오게 된다. 이렇게 말씀해주시고 jsx코드를 자바스크립트 코드로 변환하게 해주는 것이 react.createElement라고 하셨는데, 여기 강의 에서는 5분 35초 부근에 react.createElement 내부에 리액트 컴포넌트를 적어도 되고 모든 리액트 컴포넌트는 최종적으로는 html 태그를 사용하게 돼있다라고 하셨습니다. react.createElement를 통해서 최종적으로 자바스크립트가 된다는건가요? 아니면 html 코드가 된다는건가요,,?ㅠㅠ
sohee
2023-07-10T07:22:19.979Z
댓글 1
좋아요 0
조회수 449
미해결
[개정3판] Node.js 교과서 - 기본부터 프로젝트 실습까지
ejs와 cjs 둘 중 express 프레임워크를 사용해서 프로그래밍을 하려면 어떤 방식을 추천하시나요?
node.js mysql mongodb express typescript socket.io jwt
박동규
2023-07-08T06:13:07.352Z
댓글 1
좋아요 0
조회수 543
미해결
Slack 클론 코딩[실시간 채팅 with React]
react를 처음 접해보는 취준생입니다. 제가 강의를 보면서 따라하려는데 settings/js 디렉토리의 디렉토리명을 front로 변경해서 사용하고 back 디렉토리에서 npm start로 백앤드 서버 실행시키고 따라하라고 하신거 같아서 그렇게 따라하고 있습니다. 현재 localhost :3095로 접근하면 슬리액 페이지가 잘 나오는데 front 디렉토리에서 코드 수정해도 반영이 안고 있는데 혹시 어떤걸 잘 못 하고 있는지 알 수 있을까요?
react 웹팩 typescript socket.io babel 클론코딩
wlstmd9597
2023-07-08T00:51:54.131Z
댓글 1
좋아요 0
조회수 388
미해결
풀스택 리액트 라이브코딩 - 간단한 쇼핑몰 만들기
vite-plugin-next-react-router 다운받고 강의를 따라했는데요.. routes.tsx파일이 자동으로 생성이 되지않습니다. 그런데 이상하게 페이지가 작동이되요.. 이유가 뭘까요..? vite.config.ts 내용은 조금 다릅니다.reactRouterPlugin를 사용하면 오류가 생겨서 withReactRouter 으로 교체했습니다. 나머지 파일생성과 코드는 동일합니다.. import { defineConfig } from "vite"; import withReactRouter from "vite-plugin-next-react-router"; import react from "@vitejs/plugin-react"; export default defineConfig({ plugins: [react(), withReactRouter()], });
Nuri Park
2023-07-05T13:01:35.215Z
댓글 3
좋아요 0
조회수 1503
해결됨
Python 알고리즘 베스트 10
안녕하세요 PDF파일은 출력하려고 하는데, 노션을 보면 "PDF 노션 페이지에서 다운로드하실 수 있습니다." 로만 되어있는데 다운받을 수 있는 링크는 어디에 있나요? 노션에서 전체PDF출력하려면 비지니스라서 불가능한데... 확인부탁드립니다.
한형섭
2023-07-04T12:26:33.948Z
댓글 2
좋아요 0
조회수 485
미해결
파이썬/장고 웹서비스 개발 완벽 가이드 with 리액트
안녕하세요, 강의를 잘 듣고 있습니다. 모델 필드에 있는 몇몇 필드들이 admin에 나타나지 않더군요 예를 들면, updated_at, created_at 같은 필드들이요 이를 위해서 admin 페이지에 일일히 모델 필드를 list_display에 등록해줘야 하는게 맞나요? from django.contrib import admin # Register your models here. from .models import * admin.site .empty_value_display = "-empty-" admin.site .register(Product) admin.site .register(CartProduct) class OrderAdmin(admin.ModelAdmin): list_display = ['customer', 'transaction_id', 'total_price'] admin.site .register(Category) admin.site .register(UserProfile) admin.site .register(Order) admin.site .register(OrderedProduct) admin.site .register(ShipmentInfo) 그럼 제가 직접만든 모델의 경우에는 그렇다 쳐도.. allauth에 있는 site domain 부분이 나오질 않는거에요 ㅠㅠ... 제가 뭘 잘못 건드렸는 지 모르겠는데, 맨처음 프로젝트할 때에는 allauth의 소셜 어플리케이션 부분에 사이트 도메인을 입력할 수 있는 커다란 박스가 있었는데, 그것만 또 안난옵니다. 제가 뭘 잘못한건지 ㅠㅠ 원래 잘 나오던건데... 이번에 파이참 커뮤니티 에디션에서 유료버전으로 바꾸고, 프로젝트를 만들고 나니 admin에 몇몇 모델의 필드들이 잘 보이지 않습니다. verbose name을 설정된것들이 특히 그런 거 같은데 무엇이 문제인지 도통 모르겠습니다. 그렇다고 allauth를 제가 admin에 등록해야하는걸까요? 2.제가 모르는 무언가가 있는걸까요?
paichai17
2023-07-03T07:21:47.006Z
댓글 1
좋아요 0
조회수 307
해결됨
[개정3판] Node.js 교과서 - 기본부터 프로젝트 실습까지
안녕하세요 json부하테스트중에 에러표시나서 방화벽들어가서 mysql포트 확인하고 3306설정했는데 안되서 포트80도해보고 했는데 에러표시만뜹니다 https://binshuuuu.tistory.com/m/214 제가 따라한 설정입니다
node.js mysql mongodb express typescript socket.io jwt
Hongsun1
2023-07-03T05:38:55.828Z
댓글 1
좋아요 0
조회수 357
해결됨
[개정3판] Node.js 교과서 - 기본부터 프로젝트 실습까지
선생님 콘솔로그 쳐서 premium위치 찾아서req.user.Domains [5].type === 'premium' 했는데 true 나와서 해결했습니다 감사합니다 앞으로 콘솔로그 쳐서 하는 습관가져야겠습니다 정말 감사합니다 ^_^!!!
node.js mysql mongodb express typescript socket.io jwt
Hongsun1
2023-07-02T05:31:54.286Z
댓글 0
좋아요 1
조회수 299
미해결
명령어가 안 먹혀요.
SungHwan Moon
2023-06-30T14:40:54.995Z
댓글 2
좋아요 1
조회수 320
미해결
구성 관리 자동화 도구 - 앤서블(Ansible)
안녕하세요. 아래 섹션 실습 중, 에러가 발생하여 문의드립니다. 섹션 9 : [응용] 윈도우 관리학 - (1)베이그런트를 이용해서 윈도우를 추가하기 Ansible_env_ready.yaml 에 아래와 같이 추가 후, vagrant provision ansible-server을 수행했는데 pvwinrm 설치 과정에서 에러가 발생하였습니다. - name: Install python-pip yum: name: python-pip state: present - name: Install pywinrm pip: name: pywinrm state: present ansible-server에 접속하여 수동으로 pip install pywinrm을 수행했는데 역시 에러가 발생합니다. python 버전을 업그레이드 하라고 메시지가 나오는데 향후 수업 따라하기 시, 영향이 있을 듯 하여 선뜻 테스트하지 못 하고 있습니다. 해결 방법에 대해서 가이드 부탁드리겠습니다. 감사합니다 !
doore.park
2023-06-30T08:30:02.308Z
댓글 1
좋아요 0
조회수 638
미해결
Slack 클론 코딩[실시간 채팅 with React]
안녕하세요. 우선 저는 맥북을 사용하고 있습니다. import { VFC, useCallback, useEffect, useRef } from 'react'; import { Form, MentionsTextarea, SendButton, Toolbox } from './styles'; import React from 'react'; import autosize from 'autosize'; interface Props { chat: string; onSubmitForm: (e: any) => void; onChangeChat: (e: any) => void; placeholder?: string; } const ChatBox: VFC<Props> = ({ chat, onSubmitForm, onChangeChat, placeholder }) => { // const onSubmitForm = useCallback(() => {}, []); const textareaRef = useRef(null); useEffect(() => { if (textareaRef.current) { autosize(textareaRef.current); } }, []); const onKeydownChat = useCallback( (e) => { if (e.key === 'Enter') { if (!e.shiftKey) { e.preventDefault(); onSubmitForm(e); } } }, [onSubmitForm], ); return ( <Form onSubmit={onSubmitForm}> <MentionsTextarea id="editor-chat" value={chat} onChange={onChangeChat} onKeyDown={onKeydownChat} placeholder={placeholder} ref={textareaRef} /> <Toolbox> <SendButton className={ 'c-button-unstyled c-icon_button c-icon_button--light c-icon_button--size_medium c-texty_input__button c-texty_input__button--send' + (chat?.trim() ? '' : ' c-texty_input__button--disabled') } data-qa="texty_send_button" aria-label="Send message" data-sk="tooltip_parent" type="submit" disabled={!chat?.trim()} > <i className="c-icon c-icon--paperplane-filled" aria-hidden="true"></i> </SendButton> </Toolbox> </Form> ); }; export default ChatBox; 이건 제가 작성한 ChatBox입니다. import React, { useCallback } from 'react'; import { Container, Header } from './styles'; import useSWR, { useSWRInfinite } from 'swr'; import fetcher from '@utils/fetcher'; import { useParams } from 'react-router'; import gravatar from 'gravatar'; import ChatBox from '@components/ChatBox'; import ChatList from '@components/ChatList'; import useInput from '@hooks/useInput'; import axios from 'axios'; import { IDM } from '@typings/db'; const DirectMessage = () => { const { workspace, id } = useParams<{ workspace: string; id: string }>(); const { data: userData } = useSWR(`/api/workspaces/${workspace}/users/${id}`, fetcher); const { data: myData } = useSWR('/api/users', fetcher); const [chat, onChangeChat, setChat] = useInput(''); const { data: chatData, mutate: mutateChat, revalidate, } = useSWR<IDM[]>(`/api/workspaces/${workspace}/dms/${id}/chats?perPage=20&page=1`, fetcher); const onSubmitForm = useCallback( (e) => { e.preventDefault(); if (chat?.trim()) { axios .post(`/api/workspaces/${workspace}/dms/${id}/chats`, { content: chat, }) .then(() => { revalidate(); setChat(''); console.log('submit'); }) .catch((error) => { console.log(error); }); } }, [chat], ); if (!userData || !myData) { return null; } return ( <Container> <Header> <img src={gravatar.url(userData.email, { s: '24px', d: 'retro' })} alt={userData.nickname} /> <span>{userData.nickname}</span> </Header> <ChatList chatData={chatData} /> <ChatBox chat={chat} onChangeChat={onChangeChat} onSubmitForm={onSubmitForm} /> </Container> ); }; export default DirectMessage; 이건 DirectMessage 입니다. e.preventDefault()로 기본 이벤트를 막아줬는데도 DM을 엔터로 전송하면 (한글로만 전송하면 2개씩 보내져요...!)어떨때는 2개가 보내지고 어떨때는 1개가 보내져요... 네트워크나 콘솔에도 2개씩 뜨고요.. 전송버튼을 눌렀을때는 1개만 보내집니다.
react 웹팩 typescript socket.io babel 클론코딩
jjh099
2023-06-30T06:20:11.161Z
댓글 2
좋아요 0
조회수 740
해결됨
[개정3판] Node.js 교과서 - 기본부터 프로젝트 실습까지
안녕하세요 선생님 시퀄라이즈 강의를 듣는데 raw쿼리를 쓰는게 가능하더군요. spring + ibatis 로 주로 개발해와서 raw 쿼리가 익숙한데 실무에서는 시퀄라이즈 vs raw 쿼리 중에 어떤걸 많이 사용하는 편인가요..?
node.js mysql mongodb express typescript socket.io jwt
카이
2023-06-30T04:35:01.225Z
댓글 1
좋아요 1
조회수 273
해결됨
[개정3판] Node.js 교과서 - 기본부터 프로젝트 실습까지
선생님 어제 코드 감사합니다 아쉽게도 많이 배워야할것같아서 ㅠㅜ 혹시 제가 빠트린 코드가 있을까요 ? 아니면 다른부분 확인할 사항이 있을까요? 작성한 코드 올려드립니다 nodebird-api -> middlewares-> index.js const jwt = require("jsonwebtoken"); //토큰을 검사하는 미들웨어 const rateLimit = require("express-rate-limit"); const User = require("../models/user"); const { Domain } = require("../models/"); const cors = require("cors"); exports.isLoggedIn = (req, res, next) => { if (req.isAuthenticated()) { next(); } else { res.status(403).send("로그인 필요"); } }; exports.isNotLoggedIn = (req, res, next) => { if (!req.isAuthenticated()) { // 패스포트 통해서 로그인 안했으면 next(); } else { const message = encodeURIComponent("로그인한 상태입니다."); res.redirect(`/?error=${message}`); //localhost:8001? error=메시지 } }; //토근검사 exports.verifyToken = (req, res, next) => { try { res.locals.decoded = jwt.verify( req.headers.authorization, process.env.JWT_SECRET ); return next(); } catch (error) { if (error.name === "TokenExpiredError") { return res.status(419).json({ code: 419, message: "토큰이 만료되었습니다.", }); } return res.status(401).json({ code: 401, message: "유효하지 않은 토큰입니다.", }); } }; const limiter = rateLimit({ widowMs: 60 * 1000, max: (req, res) => { if (req.user?.Domains[0]?.type === "premium") { return 10; } return 1; }, handler(req, res) { res.status(this.statusCode).json({ code: this.statusCode, message: `1분에 ${ req.user?.Domains[0]?.type === "premium" ? "열" : "한" } 번만 요청 할 수 있습니다...`, }); }, }); exports.apiLimiter = async (req, res, next) => { let user; if (res.locals.decoded) { user = await User.findOne({ where: { id: res.locals.decoded.id }, include: { model: Domain }, }); } req.user = user; limiter(req, res, next); }; exports.deprecated = (req, res) => { res.status(410).json({ code: 410, message: "새로운 버전이 나왔습니다. 새로운 버전을 사용하세요", }); }; exports.corsWhenDomainMatches = async (req, res, next) => { const domain = await Domain.findOne({ where: { host: new URL(req.get("origin")).host }, }); if (domain) { cors({ origin: true, Credential: true, })(req, res, next); //미들웨어 확장패턴 } else { next(); } }; nodebird-api -> routes -> v2.js const express = require("express"); const { verifyToken, apiLimiter, corsWhenDomainMatches, } = require("../middlewares"); const { createToken, tokenTest, getMyPosts, getPostsByHashtag, } = require("../controllers/v2"); const cors = require("cors"); const router = express.Router(); router.use(corsWhenDomainMatches); router.use( cors({ origin: true, credentials: true, //쿠키요청 }) ); router.post("/token", apiLimiter, createToken); router.get("/test", verifyToken, apiLimiter, tokenTest); router.get("/posts/my", verifyToken, apiLimiter, getMyPosts); // GET /v2/posts/hashtag/:title router.get("/posts/hashtag/:title", verifyToken, apiLimiter, getPostsByHashtag); module.exports = router;
node.js mysql mongodb express typescript socket.io jwt
Hongsun1
2023-06-29T23:38:33.306Z
댓글 1
좋아요 1
조회수 447
미해결
Slack 클론 코딩[실시간 채팅 with React]
강의를 따라하는 도중에 npx sequelize db:create를 입력하였을때는 정상적으로 "Database sleact create."라는 메세지가 확인됬습니다. 그 이후로 yarn dev를 실행하니 아래와 같은 오류가 확인됬습니다. 이유가 뭘까요?ㅜㅜ
react 웹팩 typescript socket.io babel 클론코딩
Sienna
2023-06-29T11:53:01.067Z
댓글 1
좋아요 0
조회수 360
해결됨
Windows 소켓 프로그래밍 입문에서 고성능 서버까지!
안녕하세요 IOCP 관련 자료를 찾아보던 중 WSARecv/WSASend 할 때 넣어주는 WSAOVERLAPPED 구조체를 상속한 사용자 구조체를 넘겨주는 경우를 봤습니다. 이렇게도 사용이 가능하다면 WSAOVERLAPPED 를 상속받았으니 호환 될 것이고 추가적인 데이터도 담을 수 있어 도움이 되겠다는 생각입니다. 하나 궁금한 것이 있는데요 IOCP를 이용해서 넘긴 WSABUFF의 메모리영역은 커널에 의해 보호 받는다고 알고 있습니다. 마찬가지로 WSAOVERLAPPED 구조체도 커널에 의해 메모리 관리가 되는지 만약 관리가 된다면 상속을 통해 추가적으로 들어가는 정보도 관리에 포함이 되는지 궁금합니다 감사합니다~
고대괴물
2023-06-28T08:25:49.070Z
댓글 1
좋아요 0
조회수 586
해결됨
[개정3판] Node.js 교과서 - 기본부터 프로젝트 실습까지
exports.apiLimiter = async (req, res, next) => { let user; if (res.locals.decoded) { user = await User.findOne({ where: { id: res.locals.decoded.id } }); } rateLimit({ widowMs: 60 * 1000, max: user?.type === "premium" ? 10 : 1, handler(req, res) { res.status(this.statusCode).json({ code: this.statusCode, message: "1분에 열 번만 요청 할 수 있습니다...", }); }, })(req, res, next); }; Api 프리미엄고객만 1분에 열번만요청할수있게 미들웨어 확장패턴으로 만들었습니다 그런데 localhost:4000/myposts 접속해서 10 번이상새로고침해도 api가 제한이 안되고 제가작성한 게시글 목록만 뜹니다
node.js mysql mongodb express typescript socket.io jwt
Hongsun1
2023-06-27T11:00:11.649Z
댓글 1
좋아요 0
조회수 602
해결됨
[개정3판] Node.js 교과서 - 기본부터 프로젝트 실습까지
nodebird-api 미들웨어 index.js 타입이 any로 떠서 프리미엄이 체크가 안되고 계속 제가 작성한 게시글정보만 뜹니다 사용량제한 어떻게 하나요? ㅠㅠ const jwt = require("jsonwebtoken"); const rateLimit = require("express-rate-limit"); const User = require("../models/user"); exports.isLoggedIn = (req, res, next) => { if (req.isAuthenticated()) { next(); } else { res.status(403).send("로그인 필요"); } }; exports.isNotLoggedIn = (req, res, next) => { if (!req.isAuthenticated()) { next(); } else { const message = encodeURIComponent("로그인한 상태입니다."); res.redirect(`/?error=${message}`); } }; exports.verifyToken = (req, res, next) => { try { res.locals.decoded = jwt.verify( req.headers.authorization, process.env.JWT_SECRET ); return next(); } catch (error) { if (error.name === "TokenExpiredError") { return res.status(419).json({ code: 419, message: "토큰이 만료되었습니다.", }); } return res.status(401).json({ code: 401, message: "유효하지 않은 토큰입니다.", }); } }; exports.apiLimiter = rateLimit({ windowMs: 60 * 1000, // 1분 max: 1, handler(req, res) { res.status(this.statusCode).json({ code: this.statusCode, // 기본값 429 message: "1분에 한 번만 요청할 수 있습니다.", }); }, }); exports.apiLimiter = async (req, res, next) => { let user; if (res.locals.decoded) { user = await User.findOne({ where: { id: res.locals.decoded.id } }); } rateLimit({ widowMs: 60 * 1000, max: user?.type === "premium" ? 10 : 1, handler(req, res) { res.status(this.statusCode).json({ code: this.statusCode, message: "1분에 열 번만 요청 할 수 있습니다...", }); }, })(req, res, next); }; exports.deprecated = (req, res) => { res.status(410).json({ code: 410, message: "새로운 버전이 나왔습니다. 새로운 버전을 사용하세요", }); };
node.js mysql mongodb express typescript socket.io jwt
Hongsun1
2023-06-26T23:35:20.216Z
댓글 1
좋아요 0
조회수 252
미해결
[웹 개발 풀스택 코스] Node.js 프로젝트 투입 일주일 전 - 기초에서 실무까지
안녕하세요. 현재 mysql 연동하기 강의를 듣고 있는데, sql 워크벤치에서 어떻게 칼럼을 넣어야 하는지 알수있을까요?
node.js mysql mongodb express 웹-크롤링 socket.io
단오
2023-06-26T18:22:20.031Z
댓글 1
좋아요 0
조회수 412