66,000원
다른 수강생들이 자주 물어보는 질문이 궁금하신가요?
- 미해결Vue로 Nodebird SNS 만들기
start script 누락 오류가 떠서 질문드립니다
안녕하세요 제로초님 server.js만든후 express와 cross-env를 만들고 package.json에 "start": "cross-env PORT=80 NODE_ENV=production node server", 이렇게 추가도 하였습니다 그 후 npm start를 하는데 root@ip-172-31-26-247:/home/ubuntu/VUE.SNS/ch1/front# npm start npm ERR! missing script: start npm ERR! A complete log of this run can be found in: npm ERR! /root/.npm/_logs/2021-09-15T07_12_41_448Z-debug.log 이러한 오류가 뜹니다 ㅜ 무엇이 문제인지 구글링도 해보고 찾아봤는데 해결하지 못하여 질문드립니다. 피드백 주시면 감사하겠습니다! package.json { "name": "vue-nodebird-front", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "dev": "nuxt", "build": "nuxt build", "start": "cross-env PORT=80 NODE_ENV=production node server", "lint": "eslint **/*" }, "author": "", "license": "ISC", "dependencies": { "@nuxtjs/axios": "^5.13.6", "@nuxtjs/moment": "^1.6.1", "@nuxtjs/vuetify": "^1.12.1", "axios": "^0.21.1", "cross-env": "^7.0.3", "express": "^4.17.1", "lodash.throttle": "^4.1.1", "nuxt": "^2.15.7", "vue": "^2.6.14", "vuetify": "^2.5.6" }, "devDependencies": { "eslint": "^7.31.0", "eslint-plugin-vue": "^7.14.0" } } server.js const { loadNuxt, build } = require('nuxt') const app = require('express')() const isDev = process.env.NODE_ENV !== 'production' const port = process.env.PORT || 3080 async function start() { // We get Nuxt instance const nuxt = await loadNuxt(isDev ? 'dev' : 'start') // Render every route with Nuxt.js app.use(nuxt.render) // Build only in dev mode with hot-reloading if (isDev) { build(nuxt) } // Listen the server app.listen(port, '0.0.0.0') console.log('Server listening on `localhost:' + port + '`.') } start() 참고할 코드 보내드립니다!
- 미해결Vue로 Nodebird SNS 만들기
데이터 전달이 안되서 질문드립니다
안녕하세요 제로초님 복습하다 안되는 부분이 있어 질문드립니다 현재 해시태그를 클릭하면 클릭한 해시태그만 타임라인에 나오는 부분을 구현중에 있습니다. 그런데 화면상에 아무 글도 뜨지 않아 질문드려요 서버상에서는 200 제대로 뜹니다. 데브툴에도 loadPost 찍히구요. 근데 백엔드에서 비어있는 Array를 내려주는거 같아서 콘솔로 Store/posts.js 내부의 f(payload && payload.reset) { console.log('reset', payload.hashtag) const res = await this.$axios.get(`/hashtag/${payload.hashtag}?limit=10`) console.log(res) commit('loadPosts', { data: res.data, reset: true, }) return; } loadHashtagPosts안을 이렇게 확인해보니 아예 비어있는 값이 뜹니다. 그래서 백엔드의 hashtag.js를 제로초님 코딩과도 비교해보고, 왜 프론트로 데이터가 전송이 안되는지 계속 찾아보고 생각해봤는데 답이 안나와서 질문드려요 어떤 이유때문에 이런일이 벌어질수있는건가요?ㅜㅜ routes/hashtag.js router.get('/:tag', async (req, res, next) => { try { let where = {}; if (parseInt(req.query.lastId, 10)) { where = { id: { [db.Sequelize.Op.lt]: parseInt(req.query.lastId, 10) } } } const posts = await db.Post.findAll({ where, include: [{ model: db.Hashtag, where: { name: decodeURIComponent(req.params.tag) } }, { model: db.User, attributes: ['id', 'nickname'] }, { model: db.Image }, { model: db.User, as: "Likers", attributes: ['id'] }, { model: db.Post, as: 'Retweet', include: [{ model: db.User, attributes: ['id', 'nickname'] }, { model: db.Image }] }], order: [['createdAt', 'DESC']], limit: parseInt(req.query.limit, 10) || 10, }) return res.json(posts) } catch(err) { console.error(err) next(err) } }) Store/posts.js loadHashPosts: throttle(async function ({commit, state}, payload) { try { if(payload && payload.reset) { console.log('reset', payload.hashtag) const res = await this.$axios.get(`/hashtag/${payload.hashtag}?limit=10`) console.log(res) commit('loadPosts', { data: res.data, reset: true, }) return; } if(state.hasMorePost) { const lastPost = state.mainPosts[state.mainPosts.length - 1] const res = await this.$axios.get(`/hashtag/${payload.hashtag}?lastId=${lastPost && lastPost.id}&limit=10`) commit('loadPosts', { data: res.data }) return; } } catch (err) { console.error(err) } }, 3000), 참고 하실 코드 업로드해드립니다 참고로 hashtag/_id/index.vue에 팻치도 fetch({ store, params }) { return store.dispatch('posts/loadHashPosts', { hashtag: encodeURIComponent(params.id), reset: true, }) }, 연결하였고 app.js 에 router도 연결해놨습니다 계속 확인중에 있는데 GET /posts?limit=10 304 14.900 ms - - 이러한 에러? 가 터미널에 뜨는데 무슨 문제인지 모르겠습니다ㅜ
- 미해결Vue로 Nodebird SNS 만들기
작동은 잘 되는데 이해가 안되는 부분이 있어 질문 드립니다.
안녕하세요 제로초님 해쉬태그 클릭 검색하면 해당 해쉬태그 나오는 것을 구현하다 햇갈리는 부분이 있어 질문 드립니다. 개시물의 사용자를 누르면 해당 사용자의 글만 뜨는것을 구현 할때는 router.get으로 try 안에 let where = { UserId: parseInt(req.params.id, 10), RetweetId: null, }; if (parseInt(req.query.lastId, 10)) { where[db.Sequelize.Op.lt] = parseInt(req.query.lastId, 10) } 이 let where 를 통해 라스트아이디가 없을 경우를 대비했는데 이번 해쉬태그 강의 에서는 let where = {} if (parseInt(req.query.lastId, 10)) { where = { id: { [db.Sequelize.Op.lt]: parseInt(req.query.lastId, 10), } } } let where를 이렇게 빈칸으로 두는 이유가 뭔지 궁금합니다ㅜ 근데 이렇게 해도 작동은 되는데 원래 저렇게 빈칸으로 두면 모든 게시물을 다 찾는거 아닌가요??
- 미해결Vue로 Nodebird SNS 만들기
fetch가 실행이 되지 않아서 질문드립니다
fetch({store}) { return store.dispatch('posts/loadPosts') }, 이런식으로 pages/index.vue에 해놨는데 처음에는 스크롤 함수에 있는 onScroll() { if(window.scrollY + document.documentElement.clientHeight > document.documentElement.scrollHeight - 300) { if(this.hasMorePost) { this.$store.dispatch('posts/loadPosts') } } } 이거 때문에 스크롤 해야 loadPosts가 불리고 Duplicate keys detected: '4'. This may cause an update error 이러한 에러가 뜨면서 중복되서 잠시 온스크롤 함수를 주석처리 해놓고 보니 fetch가 아예 실행이 안되더라구요 도대체 어떤문제인지 햇갈려서 알수 없어서 ㅜ 연락드립니다. <template> <v-container> <post-form v-if='me' /> <div> <post-card v-for="p in mainPosts" :key="p.id" :post="p" /> </div> </v-container> </template> <script> import PostForm from '~/components/PostForm' import PostCard from '~/components/PostCard' export default { components: { PostForm, PostCard, }, data() { return { name : 'Nust.js' } }, fetch({store}) { return store.dispatch('posts/loadPosts') }, computed: { me() { return this.$store.state.users.me }, mainPosts() { return this.$store.state.posts.mainPosts }, hasMorePost() { return this.$store.state.posts.hasMorePost } }, mounted() { window.addEventListener('scroll', this.onScroll) }, beforeDestroy() { window.removeEventListener('scroll', this.onScroll) }, methods: { onScroll() { if(window.scrollY + document.documentElement.clientHeight > document.documentElement.scrollHeight - 300) { if(this.hasMorePost) { this.$store.dispatch('posts/loadPosts') } } } } } </script> <style> </style> 참고하실 풀 index.vue 코드 보내드려요!
- 미해결Vue로 Nodebird SNS 만들기
데이터 출처를 모르겠어서 질문드립니다
안녕하세요 제로초님 복습중에 햇갈리는 부분이 있어 연락드립니다. PostCard.vue 에 PostImages.vue 컴포넌트를 추가할때 <post-images :images ="post.Images" /> 할때 말입니다 post.Images할때 Images가 어디서 오는지 모르겠어서 연락드려요 쭉 데이터 거꾸로 찾아 올라가 봤는데 post는 page의 index에서 보내준거고 paged의 index.vue에서 보내준 데이터는 v-for="p in mainPosts"의 p로 보내준건데 그럼 mainPosts에 Images라는 데이터가 있어야 하는거 아닌가요??찾다가 햇갈려서 질문드립니다!!ㅜㅜ
- 미해결Vue로 Nodebird SNS 만들기
404 에러가 떠서 질문드립니다
현재 타임라인에서 다른 아이디를 선택하면 그 아이디의 팔로잉 팔로워 수 포스트 개수까지 다 보입니다. 하지만 현재 사진에서 보듯이 다른 아이디를 클릭하면 콘솔과 터미널에 404에러가 뜹니다 GET /user/3/posts?limit=10 404 10.091 ms - 151 이부분이 잘못된거 같아서 front/store/posts.js도 살펴 봤는데 제로초님과 코딩의 차이는 없어 보입니다 어디서 잘못된건지 찾다 해결이 안돼서 질문드립니다 ㅜㅜ 부탁드립니다 front/store/post.js loadPosts: throttle(async function({ commit, state }, payload) { try { if (payload && payload.reset) { const res = await this.$axios.get(`/posts?limit=10`); commit('loadPosts', { data: res.data, reset: true }) return; } if(state.hasMorePost) { const lastPost = state.mainPosts[state.mainPosts.length - 1] const res = await this.$axios.get(`/posts?lastId=${lastPost && lastPost.id}&limit=10`); commit('loadPosts', { data: res.data }); return; } } catch (err) { console.error(err) } }, 3000), loadUserPosts: throttle(async function({ commit, state }, payload) { try { if (payload && payload.reset) { const res = await this.$axios.get(`/user/${payload.userId}/posts?limit=10`); commit('loadPosts', { data: res.data, reset: true }) return; } if(state.hasMorePost) { const lastPost = state.mainPosts[state.mainPosts.length - 1] const res = await this.$axios.get(`/user/${payload.userId}/posts?lastId=${lastPost && lastPost.id}&limit=10`); commit('loadPosts', { data: res.data, }); return; } } catch (err) { console.error(err) } }, 3000),
- 미해결Vue로 Nodebird SNS 만들기
팔로우 팔로잉 관계가 작동하지 않습니다ㅜ
안녕하세요! 제로초님 처럼 팔로잉 팔로워 관계를 확인해 보려고 6개의 아이디를 가입후에 하나로 5개의 아이디를 팔로우하여 프로필에 들어갔는데 아이디 2 3 4는 팔로우해도 뜨지 않고 아이디 5와 6만 프로필에 뜹니다. 게다가 제로초님 처럼 가로로 3개씩 안나오고 세로로 뜨네요ㅜ 이런 식으로 팔로우를 했는데 이렇게 5와 6만 뜹니다 팔로잉에요 제로초님 코딩과 비교해보고, 테이블도 다 드랍해보고 해봐도 같은현상이 반복됩니다 ㅜ 무슨문제인지 알 수 있을까요?? routes/user.js router.post('/:id/follow', isLoggedIn, async (req, res, next) => { try { const me = await db.User.findOne({ where: { id: req.user.id } }); await me.addFollowing(req.params.id) res.send(req.params.id) } catch (err) { console.error(err) next(err) } }) router.delete('/:id/follow', isLoggedIn, async (req, res, next) => { try { const me = await db.User.findOne({ where: { id: req.user.id } }); await me.removeFollowing(req.params.id) res.send(req.params.id) } catch (err) { console.error(err) next(err) } }) router.get('/:id/followings', isLoggedIn, async (req, res, next) => { try { const user = await db.User.findOne({ where: { id: req.user.id}, }) const followings = await user.getFollowings({ attributes: ['id', 'nickname'], limit: parseInt(req.query.limit || 3, 10), offset: parseInt(req.query.limit || 0, 10) }) res.json(followings) } catch (err) { console.error(err) next(err) } }) router.get('/:id/followers', isLoggedIn, async (req, res, next) => { try { const user = await db.User.findOne({ where: { id: req.user.id}, }) const followers = await user.getFollowers({ attributes: ['id', 'nickname'], limit: parseInt(req.query.limit || 3, 10), offset: parseInt(req.query.limit || 0, 10) }) res.json(followers) } catch (err) { console.error(err) next(err) } }) router.delete('/:id/follower', isLoggedIn, async (req, res, next) => { try { const me = await db.User.findOne({ where: {id: req.user.id} }) await me.removeFollower(req.params.id) res.send(req.params.id) } catch (err) { console.error(err) next(err) } }) store/users.js mutations loadFollowing(state, payload) { if(payload.offset === 0) { state.followingList = payload.data } else { state.followingList = state.followingList.concat(payload.data); } state.hasMoreFollowing = payload.data.length === limit }, loadFollower(state, payload) { if(payload.offset === 0) { state.followerList = payload.data } else { state.followerList = state.followerList.concat(payload.data); } state.hasMoreFollower = payload.data.length === limit }, following(state, payload) { state.me.Followings.push({ id: payload.userId }) }, actions loadFollowing({commit, state}, payload) { if(!(payload && payload.offset === 0) && !state.hasMoreFollowing) { return } let offset = state.followingList.length; if(payload && payload.offset === 0) { offset = 0; } return this.$axios.get(`/user/${state.me.id}/followings?limit=3&offset=${offset}`, { withCredentials: true }) .then((res) => { commit('loadFollowing', { data: res.data, offset, }) }) .catch((err) => { console.error(err) }) }, loadFollower({commit, state}, payload) { if(!(payload && payload.offset === 0) && !state.hasMoreFollower) { return } let offset = state.followerList.length; if(payload && payload.offset === 0) { offset = 0; } return this.$axios.get(`/user/${state.me.id}/followers?limit=3&offset=${offset}`, { withCredentials: true }) .then((res) => { commit('loadFollower', { data: res.data, offset, }) }) .catch((err) => { console.error(err) }) }, follow({commit, state}, payload) { this.$axios.post(`/user/${payload.userId}/follow`, {}, { withCredentials: true, }) .then(() => { commit('following', { userId: payload.userId }) }) .catch((err) => { console.error(err); }) }, unFollow({commit, state}, payload) { return this.$axios.delete(`/user/${payload.userId}/follow`, { withCredentials: true, }) .then(() => { commit('removeFollowing', { userId: payload.userId }) }) .catch((err) => { console.error(err); }) }, 뷰 데브툴과 네티워크 탭에서도 이상은 보이지 않습니다. 뷰데브툴에서도 팔로우 언팔로우 누르면 following removefollosing 찍히구요 네트워크 탭에서도 200으로 잘찍힙니다
- 미해결Vue로 Nodebird SNS 만들기
nuxtServerInit 이후로 오류가 뜹니다 ㅜ
안녕하세요 제로초님 기존 질문 확인해봤는데 해결하는데 어려움이 있어 질문드립니다. store/index.js에 export const state = () => ({}); export const mutations = {} export const actions = { nuxtServerInit({commit, dispatch, state}, {req}) { return dispatch('users/loadUser') } } 이렇게 넉스트서버 인잇 한 이후에 이렇게 콘솔과 터미널에 에러가 뜸니다 ㅜ store/users.js async loadUser({state, commit}) { try { const res = await this.$axios.get('/user', { withCredentials: true, }) console.log(res.data); commit('setMe', res.data) console.log(state) } catch (err) { console.error(err) } }, 이 코드 보시면 loadUser 액션에서도 틀린 부분은 없는것 같은데 무슨 문제인지 해결하는데 어려워서 질문드립니다ㅜㅜ!! 근데 오류가 뜨긴 하지만 새로고침하면 로그인 상태 유지도 되고 이상은 없어 보이긴 합니다. 근데 그냥 내비 두는게 나중에 큰 문제를 발생시킬거 같아서 질문드려요!ㅜ
- 미해결Vue로 Nodebird SNS 만들기
미들웨어 프론트로 알려주는 방법
안녕하세요 미들웨어를 사용중입니다. 문제가 있는경우 res.status.send로 값을 전달하는데 이렇게 전달하는 값들을 프론트에서 alert이나 팝업으로 띄울 수 있을까요? 예를들어 포스트에 isloggedin을 넣게 되면 401에러와 함께 포스트가 불러오지 않는데 유저들은 그걸 알 수 없으니 미들웨어에서 res.send값 정도는 경고창이나 팝업으로 띄우고 싶습니다.
- 미해결Vue로 Nodebird SNS 만들기
이미지 업로드가 안돼서 질문드립니다
5-4 강의 마지막에 제로초님은 설정한대로 사진 2개 3개 업로드가 되는데 errors: [ ValidationErrorItem { message: 'Image.email cannot be null', type: 'notNull Violation', path: 'email', value: null, origin: 'CORE', instance: [Image], validatorKey: 'is_null', validatorName: null, validatorArgs: [] } ] } SequelizeValidationError: notNull Violation: Image.email cannot be null at InstanceValidator._validate (C:\Users\com\vue강좌\vuesns\ch1\back\node_modules\sequelize\lib\instance-validator.js:78:13) at processTicksAndRejections (internal/process/task_queues.js:93:5) at async InstanceValidator._validateAndRunHooks (C:\Users\com\vue강좌\vuesns\ch1\back\node_modules\sequelize\lib\instance-validator.js:111:7) at async InstanceValidator.validate (C:\Users\com\vue강좌\vuesns\ch1\back\node_modules\sequelize\lib\instance-validator.js:93:12) at async model.save (C:\Users\com\vue강좌\vuesns\ch1\back\node_modules\sequelize\lib\model.js:3890:7) at async Function.create (C:\Users\com\vue강좌\vuesns\ch1\back\node_modules\sequelize\lib\model.js:2207:12) at async Promise.all (index 0) at async C:\Users\com\vue강좌\vuesns\ch1\back\routes\post.js:46:32 POST /post 500 17.596 ms - 1119 이러한 업로드가 떠서 더이상 진행이 되지 않아 질문드려요 ch1\back\routes\post.js:46:32 이부분에 오류인거 같아 확인해보았는데 if(req.body.image) { if(Array.isArray(req.body.image)) { const images = await Promise.all(req.body.image.map((image) => { return db.Image.create({ src: image, PostId: newPost.id }) })) } else { const image = await db.Image.create({ src: req.body.image, PostId: newPost.id}) } } 정확히는 const images 의 await바로 앞입니다. 어떤부분이 잘못된지 모르겠어 제로초님의 코드랑 비교해봤는데 답이 나오지 않아 질문드려요 ㅜ
- 미해결Vue로 Nodebird SNS 만들기
게시물 업로드가 되지 않아 질문드려요!ㅜ
4-17강의 거의다 듣다 게시물 포스트가 되지 않아 질문드려요 네트워크 창에서는 에러 500이라 뜨고, 터미널에서는 유저 이메일, 패스워드, 닉네임이 널이 되면 안된다 하는데 ValidationError [SequelizeValidationError]: notNull Violation: User.email cannot be null, notNull Violation: User.nickname cannot be null, notNull Violation: User.password cannot be null at InstanceValidator._validate (C:\Users\com\vue강좌\복습\back\node_modules\sequelize\lib\instance-validator.js:78:13) at processTicksAndRejections (internal/process/task_queues.js:93:5) at async InstanceValidator._validateAndRunHooks (C:\Users\com\vue강좌\복습\back\node_modules\sequelize\lib\instance-validator.js:111:7) at async InstanceValidator.validate (C:\Users\com\vue강좌\복습\back\node_modules\sequelize\lib\instance-validator.js:93:12) at async model.save (C:\Users\com\vue강좌\복습\back\node_modules\sequelize\lib\model.js:3890:7) at async Function.create (C:\Users\com\vue강좌\복습\back\node_modules\sequelize\lib\model.js:2207:12) at async C:\Users\com\vue강좌\복습\back\routes\post.js:32:21 { errors: [ ValidationErrorItem { message: 'User.email cannot be null', type: 'notNull Violation', path: 'email', value: null, origin: 'CORE', instance: [User], validatorKey: 'is_null', validatorName: null, validatorArgs: [] }, ValidationErrorItem { message: 'User.nickname cannot be null', type: 'notNull Violation', path: 'nickname', value: null, origin: 'CORE', instance: [User], validatorKey: 'is_null', validatorName: null, validatorArgs: [] }, ValidationErrorItem { message: 'User.password cannot be null', type: 'notNull Violation', path: 'password', value: null, origin: 'CORE', instance: [User], validatorKey: 'is_null', validatorName: null, validatorArgs: [] } ] } SequelizeValidationError: notNull Violation: User.email cannot be null, notNull Violation: User.nickname cannot be null, notNull Violation: User.password cannot be null at InstanceValidator._validate (C:\Users\com\vue강좌\복습\back\node_modules\sequelize\lib\instance-validator.js:78:13) at processTicksAndRejections (internal/process/task_queues.js:93:5) at async InstanceValidator._validateAndRunHooks (C:\Users\com\vue강좌\복습\back\node_modules\sequelize\lib\instance-validator.js:111:7) at async InstanceValidator.validate (C:\Users\com\vue강좌\복습\back\node_modules\sequelize\lib\instance-validator.js:93:12) at async model.save (C:\Users\com\vue강좌\복습\back\node_modules\sequelize\lib\model.js:3890:7) at async Function.create (C:\Users\com\vue강좌\복습\back\node_modules\sequelize\lib\model.js:2207:12) at async C:\Users\com\vue강좌\복습\back\routes\post.js:32:21 POST /post 500 21.201 ms - 1150 구글링도 해보고 찾아 봤는데 방법이 안나와 질문 드립니다. 유저 이메일 등이 잘못 설정이 된거면 도대체 어디에서 잘못된건지 만진적이 없는거 같은데 ㅜ 도와주시면 감사하겠습니다 참고로 코딩페이지 보내드리겠습니다 routes/post.js(백엔드) const express = require('express') const multer = require('multer') const path = require('path') const db = require('../models') const { isLogedIn, isNotLogedIn } = require('./middlewares') const router = express.Router() const upload = multer({ storage: multer.diskStorage({ destination(req, file, done) { done(null, 'uploads'); }, filename(req, file, done) { const ext = path.extname(file.originalname) const basename = path.basename(file.originalname, ext) done(null, basename + Date.now() + ext) } }), limit: { fileSize: 20 * 1024 * 1024} }) router.post('/images', isLogedIn, upload.array('image'), (req, res) => { console.log(req.files); res.json(req.files.map(v => v.filename)); }) router.post('/', isLogedIn, async (req, res, next) => { try { const hashtags = req.body.content.match(/#[^\s#]+/g); const newPost = await db.Post.create({ content: req.body.content, UserId: req.user.id, }); if (hashtags) { const result = await Promise.all(hashtags.map(tag => db.Hashtag.findOrCreate({ where: { name: tag.slice(1).toLowerCase() }, }))); await newPost.addHashtags(result.map(r => r[0])); } const fullPost = await db.Post.findOne({ where: { id: newPost.id }, include: [{ model: db.User, attributes: ['id', 'nickname'], }], }); return res.json(fullPost); } catch (err) { console.error(err); next(err); } }); module.exports = router PostForm.vue(프론트엔드) <template> <v-card style="margin-bottom: 20px"> <v-container> <v-form ref="form" v-model="valid" @submit.prevent="onSubmitForm"> <v-textarea outlined auto-grow clearable v-model="content" label="어떤 신기한 일이 있었나요?" :hide-details="hideDetails" :success-messages="successMessages" :success="success" :rules="[v => !!v || '내용을 입력해라']" @input="onChangeTextarea" /> <v-btn type="submit" color="green" absolute right>짹짹</v-btn> <input ref="imageInput" type="file" multiple hidden @change ="onChangeImages"> <v-btn @click="onClickImageUpload" type="button">이미지 업로드</v-btn> <div> <div v-for="(p, i) in imagePaths" :key="p" style="display: inline-block"> <img :src="`http://localhost:3085/${p}`" :alt="p" style="width: 200px"> <div> <button @click="onRemoveImage(i)" type="button">제거</button> </div> </div> </div> </v-form> </v-container> </v-card> </template> <script> import { mapState } from 'vuex' export default { data() { return { valid: false, hideDetails: false, successMessages: '', success: false, content: '', } }, computed: { ...mapState('users', ['me']), ...mapState('posts', ['imagePaths']) }, methods: { onChangeTextarea(value) { if(value.length) { this.hideDetails = true; this.success = false; this.successMessages = ''; } }, onSubmitForm() { if(this.$refs.form.validate()) { this.$store.dispatch('posts/add', { content : this.content, }) .then(() => { this.content = '', this.hideDetails = false; this.success = true; this.successMessages = '게시글 등록 성공'; }) .catch(() => { }) } }, onClickImageUpload() { this.$refs.imageInput.click(); }, onChangeImages(e) { console.log(e.target.files) const imageFormData = new FormData(); [].forEach.call(e.target.files, (f) => { imageFormData.append('image', f) }) this.$store.dispatch('posts/uploadImages', imageFormData) }, onRemoveImage(index) { this.$store.commit('posts/removeImagePaths', index) } } } </script> <style> </style> posts.js(프론트엔드) export const state = () => ({ mainPosts: [], hasMorePost: true, imagePaths: [] }) const limit = 10; const totalPosts = 51 export const mutations = { addMainPosts(state, payload) { state.mainPosts.unshift(payload); state.imagePaths = []; }, removeMainPosts(state, payload) { const index = state.mainPosts.findIndex(v => v.id === payload.id); state.mainPosts.splice(index, 1) }, addComment(state, payload) { const index = state.mainPosts.findIndex(v => v.id === payload.postId); state.mainPosts[index].Comments.unshift(payload) }, loadPosts(state, payload) { const diff = totalPosts - state.mainPosts.length const fakePosts = Array(diff > limit ? limit : diff).fill().map(v => ({ id: Math.random().toString(), User: { id: 1, nickname: "Moon" }, content: `hello infinite scrolling ${Math.random()}`, Comments: [], Img: [], })) state.mainPosts = state.mainPosts.concat(fakePosts) state.hasMorePost = fakePosts.length === limit }, concatImagePaths(state, payload) { state.imagePaths = state.imagePaths.concat(payload) }, removeImagePaths(state, payload) { state.imagePaths.splice(payload, 1) } } export const actions = { add({commit, state}, payload) { this.$axios.post('http://localhost:3085/post', { content: payload.content, imagePaths: state.imagePaths, }, { withCredentials: true }) .then((res) => { commit('addMainPosts', res.data) }) .catch(() => { }) }, remove({commit}, payload) { commit('removeMainPosts', payload) }, addComment({commit}, payload) { commit('addComment', payload) }, loadPosts({commit, state}, payload) { if(state.hasMorePost) { commit('loadPosts', payload) } }, uploadImages({ commit }, payload) { this.$axios.post('http://localhost:3085/post/images', payload, { withCredentials: true, }) .then((res) => { commit('concatImagePaths', res.data); }) .catch(() => { }) } }
- 미해결Vue로 Nodebird SNS 만들기
500 status
안녕하세요 강사님회원가입 후에 user stauts 500으로 떠서 무엇이 문제인지 모르겠어서 질문드려요회원가입을하면 터미널에서 이상한 오류?가 뜹니다 ValidationError [SequelizeValidationError]: notNull Violation: User.email cannot be null, notNull Violation: User.nickname cannot be null, notNull Violation: User.password cannot be null at InstanceValidator._validate (C:\Users\com\vue강좌\복습\back\node_modules\sequelize\lib\instance-validator.js:78:13) at processTicksAndRejections (internal/process/task_queues.js:93:5) at async InstanceValidator._validateAndRunHooks (C:\Users\com\vue강좌\복습\back\node_modules\sequelize\lib\instance-validator.js:111:7) at async InstanceValidator.validate (C:\Users\com\vue강좌\복습\back\node_modules\sequelize\lib\instance-validator.js:93:12) at async model.save (C:\Users\com\vue강좌\복습\back\node_modules\sequelize\lib\model.js:3890:7) at async Function.create (C:\Users\com\vue강좌\복습\back\node_modules\sequelize\lib\model.js:2207:12) at async C:\Users\com\vue강좌\복습\back\app.js:18:25 { errors: [ ValidationErrorItem { message: 'User.email cannot be null', type: 'notNull Violation', path: 'email', value: null, origin: 'CORE', instance: [User], validatorKey: 'is_null', validatorName: null, validatorArgs: [] }, ValidationErrorItem { message: 'User.nickname cannot be null', type: 'notNull Violation', path: 'nickname', value: null, origin: 'CORE', instance: [User], validatorKey: 'is_null', validatorName: null, validatorArgs: [] }, ValidationErrorItem { message: 'User.password cannot be null', type: 'notNull Violation', path: 'password', value: null, origin: 'CORE', instance: [User], validatorKey: 'is_null', validatorName: null, validatorArgs: [] } ] } SequelizeValidationError: notNull Violation: User.email cannot be null, notNull Violation: User.nickname cannot be null, notNull Violation: User.password cannot be null at InstanceValidator._validate (C:\Users\com\vue강좌\복습\back\node_modules\sequelize\lib\instance-validator.js:78:13) at processTicksAndRejections (internal/process/task_queues.js:93:5) at async InstanceValidator._validateAndRunHooks (C:\Users\com\vue강좌\복습\back\node_modules\sequelize\lib\instance-validator.js:111:7) at async InstanceValidator.validate (C:\Users\com\vue강좌\복습\back\node_modules\sequelize\lib\instance-validator.js:93:12) at async model.save (C:\Users\com\vue강좌\복습\back\node_modules\sequelize\lib\model.js:3890:7) at async Function.create (C:\Users\com\vue강좌\복습\back\node_modules\sequelize\lib\model.js:2207:12) at async C:\Users\com\vue강좌\복습\back\app.js:18:25 ValidationError [SequelizeValidationError]: notNull Violation: User.email cannot be null, notNull Violation: User.nickname cannot be null, notNull Violation: User.password cannot be null at InstanceValidator._validate (C:\Users\com\vue강좌\복습\back\node_modules\sequelize\lib\instance-validator.js:78:13) at processTicksAndRejections (internal/process/task_queues.js:93:5) at async InstanceValidator._validateAndRunHooks (C:\Users\com\vue강좌\복습\back\node_modules\sequelize\lib\instance-validator.js:111:7) at async InstanceValidator.validate (C:\Users\com\vue강좌\복습\back\node_modules\sequelize\lib\instance-validator.js:93:12) at async model.save (C:\Users\com\vue강좌\복습\back\node_modules\sequelize\lib\model.js:3890:7) at async Function.create (C:\Users\com\vue강좌\복습\back\node_modules\sequelize\lib\model.js:2207:12) at async C:\Users\com\vue강좌\복습\back\app.js:18:25 { errors: [ ValidationErrorItem { message: 'User.email cannot be null', type: 'notNull Violation', path: 'email', value: null, origin: 'CORE', instance: [User], validatorKey: 'is_null', validatorName: null, validatorArgs: [] }, ValidationErrorItem { message: 'User.nickname cannot be null', type: 'notNull Violation', path: 'nickname', value: null, origin: 'CORE', instance: [User], validatorKey: 'is_null', validatorName: null, validatorArgs: [] }, ValidationErrorItem { message: 'User.password cannot be null', type: 'notNull Violation', path: 'password', value: null, origin: 'CORE', instance: [User], validatorKey: 'is_null', validatorName: null, validatorArgs: [] } ] } SequelizeValidationError: notNull Violation: User.email cannot be null, notNull Violation: User.nickname cannot be null, notNull Violation: User.password cannot be null at InstanceValidator._validate (C:\Users\com\vue강좌\복습\back\node_modules\sequelize\lib\instance-validator.js:78:13) at processTicksAndRejections (internal/process/task_queues.js:93:5) at async InstanceValidator._validateAndRunHooks (C:\Users\com\vue강좌\복습\back\node_modules\sequelize\lib\instance-validator.js:111:7) at async InstanceValidator.validate (C:\Users\com\vue강좌\복습\back\node_modules\sequelize\lib\instance-validator.js:93:12) at async model.save (C:\Users\com\vue강좌\복습\back\node_modules\sequelize\lib\model.js:3890:7) at async Function.create (C:\Users\com\vue강좌\복습\back\node_modules\sequelize\lib\model.js:2207:12) at async C:\Users\com\vue강좌\복습\back\app.js:18:25 이러한 글이 뜹니다.
- 미해결Vue로 Nodebird SNS 만들기
배포하면 https로만 요청이 갑니다 ㅠ
배포 시에 process.env.PORT가 80, process.env.NODE_ENV가 'production'인 것은 잘 확인하였습니다. 문제가 로컬에서 개발 모드 시에는 http 프로토콜로 잘 보내서 서버가 잘 처리하는데, 배포모드일 때만 다음 사진과 같이 https로만 보내서 ERR_CONNECTION_REFUSED 에러가 나더군요 ㅠ 포스트맨에서 http로 보냈을 때는 잘 응답하고, 명시적으로 https로 보냈을 때 위 브라우저와 같은 에러를 뿜는 것을 보니 브라우저에서 배포일 때 항상 https로 요청을 날려서 나는 문제인 것을 확인했습니다 ㅠ 참고로 아직 https 셋팅은 하지도 않았고, nuxt.config.js에서도 다음과 같이 axios 설정을 https 날리지 않게 했는데도 불구하고 왜 https로만 날리는지 모르겠네요 ㅠ 참고로 이게 로컬에서 개발 모드로 프론트 백엔드 띄웠을 때는 잘 왔다 갔다 하는데 배포에서 돌릴 때만 저 문제가 발생해요 ㅠㅠ
- 미해결Vue로 Nodebird SNS 만들기
강의 듣는중 에러가 떠서 질문 드립니다 ㅜ
이러한 에러가 뜨는데 어디서부터 무엇이 잘못된건지 햇갈리네요 ㅜ 왜 이런 에러가 뜨는 걸까요?? [nodemon] restarting due to changes... [nodemon] starting `node app.js` internal/modules/cjs/loader.js:883 throw err; ^ Error: Cannot find module '/../config/config.json' Require stack: - C:\Users\com\vue강좌\라우터복습\ch4\back\models\index.js - C:\Users\com\vue강좌\라우터복습\ch4\back\app.js at Function.Module._resolveFilename (internal/modules/cjs/loader.js:880:15) at Function.Module._load (internal/modules/cjs/loader.js:725:27) at Module.require (internal/modules/cjs/loader.js:952:19) at require (internal/modules/cjs/helpers.js:88:18) at Object.<anonymous> (C:\Users\com\vue강좌\라우터복습\ch4\back\models\index.js:3:16) at Module._compile (internal/modules/cjs/loader.js:1063:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10) at Module.load (internal/modules/cjs/loader.js:928:32) at Module.require (internal/modules/cjs/loader.js:952:19) { code: 'MODULE_NOT_FOUND', requireStack: [ 'C:\\Users\\com\\vue강좌\\라우터복습\\ch4\\back\\models\\index.js', 'C:\\Users\\com\\vue강좌\\라우터복습\\ch4\\back\\app.js' ] } [nodemon] app crashed - waiting for file changes before starting...
- 미해결Vue로 Nodebird SNS 만들기
게시물의 아이디를 클랙하면 "This page could not be found" 이렇게 뜹니다
안녕하세요 pages에서 user폴더 id폴더 안에 index.vue만들어서 pages에 원래 있는 index.vue 내용을 복사하는 것까지는 잘 됬는데 페이지에서 게시물 아이디를 클릭하면 이렇게 뜹니다 ㅜ 무엇이 문제 일까요?ㅜ
- 미해결Vue로 Nodebird SNS 만들기
LoadPostsrk가 실행이 안됩니다 ㅜ
안녕하세요 보시는것처럼 작성하여 loadPosts를 확인해보려했는데 실행이 안됩니다 ㅜ console.log('in') 이나 hasMorePosts를 콜솔로 찍어보려 console.log를 쳐서 저장하거나 console.log텍스트를 삭제하고 저장하면 그때 마다 화면 스크롤을 움직이지도 않았는데 loadPosts가 찍히고, 더비 포스트(fakePosts로 만들어 놓은것)이 양이 많아지는 현상이 나타납니다. 무엇이 잘못된지 알수 있을까요??
- 미해결Vue로 Nodebird SNS 만들기
팔로우 팔로잉이 보이지 않아서 질문드려요 ㅜ
보시는 바와 같이 코딩을 했는데 오류가 뜨며 팔로ㅇ잉 팔로우 더미 데이터가 보이지가 않습니다 ㅜ 어떻게 해야할까요 ㅜ
- 미해결Vue로 Nodebird SNS 만들기
마지막 댓글이 포스트 되지 않습니다 ㅜ
보시는 바와 같이 댓글을 쓰고 '삐약' 버튼을 눌러 포스트 하려 하는데 이러한 에러가 뜹니다 어떻게 해아 할까요 사실 전에는 unshift가 undefined라고 떠서 그냥 야예 다시 해본건데 이번에는 Comment가 undefined라고 뜨네요 ㅜㅜ
- 해결됨Vue로 Nodebird SNS 만들기
뷰랑 노드같이쓰려면
질문이 있습니다. 노드강좌에서는 넌적스나 퍼그같은 템플릿엔진을 사용했는데 이때는 익스프레스 서버 하나만 돌려도 웹페이지 구동시킬수 있었는데 뷰랑 노드쓰려면 프론트서버 따로두고 백엔드서버도 따로두는 방법밖에 없나요 ? 노드에서 템플릿 엔진 쓴것처럼 익스프레스 서버하나에 뷰를 보여주는 방법은 없나요? 있다면 어떤 키워드로 검색하는것이 좋을까요?
- 미해결Vue로 Nodebird SNS 만들기
npm run lint 부터 오류가 생겨 진행이 되지 않습니다 ㅜㅜ
안녕하세요 eslint 설치하고 npm run lint를 하는데 이렇게 에러가 뜸니다 어떻게 해야할지 모르겠어 질문 남깁니다. 답변주시면 감사하겠습니다!!