Commit 94ab062d authored by Lee SeoYeon's avatar Lee SeoYeon
Browse files

.

parent 72dcf80a
This diff is collapsed.
import React, { useState, useEffect } from 'react' import React, { useState, useEffect } from 'react'
import { Alert, Col, Card, Container, Form, Row, Button, Nav, Navbar, ListGroup, Image, Table } from "react-bootstrap" import { Alert, Col, Card, Container, Form, Row, Button, Nav, Navbar, ListGroup, Image, Table } from "react-bootstrap"
import axios from "axios" import axios from "axios"
import catchErrors from './utils/catchErrors.js'
import { Redirect } from 'react-router-dom' import { Redirect } from 'react-router-dom'
const INIT_PAGE = { const INIT_PAGE = {
...@@ -11,14 +12,21 @@ const INIT_PAGE = { ...@@ -11,14 +12,21 @@ const INIT_PAGE = {
function Bookmark() { function Bookmark() {
const [page, setPage] = useState(INIT_PAGE) const [page, setPage] = useState(INIT_PAGE)
const [success, setSuccess] = useState(false) const [success, setSuccess] = useState(false)
const [error, setError] = useState('')
function handleChange(event) {
const {title, value} = event.target
setPage({...page, [title]: value})
}
async function handleSubmit(event) { async function handleSubmit(event) {
event.preventDefault() event.preventDefault()
try { try {
setError('') setError('')
const response = await axios.post('/api/users/', user) const response = await axios.post('/api/users/bookmark ', page)
console.log(response.data) console.log(response.data)
console.log(user) console.log(page)
// setUser(INIT_USER) // setUser(INIT_USER)
setSuccess(true) setSuccess(true)
} catch (error) { } catch (error) {
......
...@@ -9,27 +9,28 @@ import { handleLogin } from '../utils/auth' ...@@ -9,27 +9,28 @@ import { handleLogin } from '../utils/auth'
const INIT_USER = { const INIT_USER = {
email: '', email: '',
password: '' password: ''
} } //초기 유저에 이메일 비밀번호 설정
function Login() { function Login() {
//const [<상태 값 저장 변수>, <상태 값 갱신 함수>] = useState(<상태 초기 값>);
const [user, setUser] = useState(INIT_USER) const [user, setUser] = useState(INIT_USER)
const [disabled, setDisabled] = useState(true) const [disabled, setDisabled] = useState(true)
const [error, setError] = useState('') const [error, setError] = useState('')
const [success, setSuccess] = useState(false) const [success, setSuccess] = useState(false)
const [loading, setLoading] = useState(false) const [loading, setLoading] = useState(false)
useEffect(() => { useEffect(() => { //참거짓 판단 값들의 원소들이 element로 들어간다
const isUser = Object.values(user).every(el => Boolean(el)) const isUser = Object.values(user).every(el => Boolean(el))
isUser ? setDisabled(false) : setDisabled(true) isUser ? setDisabled(false) : setDisabled(true)
}, [user]) }, [user])
function handleChange(event) { function handleChange(event) {
const {name, value} = event.target const {name, value} = event.target //{}안에 값을 이벤트.타겟에 지정?한다
setUser({...user, [name]: value}) setUser({...user, [name]: value})
} }
async function handleSubmit(event) { async function handleSubmit(event) {
event.preventDefault() event.preventDefault() //리셋을 막는다
try { try {
setLoading(true) setLoading(true)
setError('') setError('')
...@@ -46,7 +47,7 @@ function Login() { ...@@ -46,7 +47,7 @@ function Login() {
if (success) { if (success) {
console.log('success', success) console.log('success', success)
return <Redirect to= '/'/> return <Redirect to= '/'/> //성공하면 홈화면으로 간다
} }
return ( return (
......
...@@ -3,9 +3,9 @@ import React, { useEffect, useState } from 'react'; ...@@ -3,9 +3,9 @@ import React, { useEffect, useState } from 'react';
import { Modal, Container, Row, Col, Button, Badge, Card, Accordion, Carousel } from 'react-bootstrap'; import { Modal, Container, Row, Col, Button, Badge, Card, Accordion, Carousel } from 'react-bootstrap';
function Place(props) { function Place(props) {
const [reviews, setReviews] = useState([]) const [reviews, setReviews] = useState([])
const getReview = () => { const getReview = () => { //review를 서버에 연결해서
axios.get(`/api/review/${props.search.name}`) axios.get(`/api/review/${props.search.name}`)
.then(res => { .then(res => {
console.log("place res.data", res.data) console.log("place res.data", res.data)
setReviews(res.data) setReviews(res.data)
......
import React from 'react' import React from 'react'
import { Route, Redirect } from 'react-router-dom' import { Route, Redirect } from 'react-router-dom'
import { isAuthenticated } from "../utils/auth"; import { isAuthenticated } from "../utils/auth";
//로그인 했을때 경로 실행하게 한다
function PrivateRoute({path, children}) { function PrivateRoute({path, children}) {
if (isAuthenticated()) { if (isAuthenticated()) {
return ( return (
......
...@@ -8,10 +8,10 @@ const INIT_USER = { ...@@ -8,10 +8,10 @@ const INIT_USER = {
name: '', name: '',
email: '', email: '',
password: '' password: ''
} } // 초기유저에 이름, 이메일, 비밀번호를 빈배열로 지정한다.
function Signup() { function Signup() {
const [user, setUser] = useState(INIT_USER) const [user, setUser] = useState(INIT_USER)
const [disabled, setDisabled] = useState(true) const [disabled, setDisabled] = useState(true)
const [error, setError] = useState('') const [error, setError] = useState('')
const [success, setSuccess] = useState(false) const [success, setSuccess] = useState(false)
...@@ -20,16 +20,16 @@ function Signup() { ...@@ -20,16 +20,16 @@ function Signup() {
const isUser = Object.values(user).every(el => Boolean(el)) const isUser = Object.values(user).every(el => Boolean(el))
isUser ? setDisabled(false) : setDisabled(true) isUser ? setDisabled(false) : setDisabled(true)
}, [user]) }, [user])
//바뀌는것이 있을때 이벤트가 발생하는 함수?
function handleChange(event) { function handleChange(event) {
const {name, value} = event.target const {name, value} = event.target
setUser({...user, [name]: value}) setUser({...user, [name]: value})
} }
async function handleSubmit(event) { async function handleSubmit(event) {
event.preventDefault() event.preventDefault() //submit을 누르면 이벤트가 실행
try { try {
setError('') setError('') //post로 경로를 지정해서 서버에서 값을 받는다
const response = await axios.post('/api/users/signup', user) const response = await axios.post('/api/users/signup', user)
console.log(response.data) console.log(response.data)
console.log(user) console.log(user)
...@@ -40,7 +40,7 @@ function Signup() { ...@@ -40,7 +40,7 @@ function Signup() {
catchErrors(error, setError) catchErrors(error, setError)
} }
} }
//성공시 알림창이 뜨고 원래 페이지로 돌아간다
if (success) { if (success) {
alert('회원가입 되었습니다.') alert('회원가입 되었습니다.')
return <Redirect to='/'/> return <Redirect to='/'/>
......
...@@ -3,10 +3,16 @@ import { Link, Redirect } from 'react-router-dom'; ...@@ -3,10 +3,16 @@ import { Link, Redirect } from 'react-router-dom';
import ohuh from './ohuh-sm.PNG'; import ohuh from './ohuh-sm.PNG';
import Place from './Components/Place'; import Place from './Components/Place';
import { Container, Form, Row, Col, Card, Image, InputGroup, FormControl, Button, Modal } from 'react-bootstrap'; import { Container, Form, Row, Col, Card, Image, InputGroup, FormControl, Button, Modal } from 'react-bootstrap';
import Paginations from './pagination.js'; import Paginations from './Components/Paginations.js'
import catchErrors from './utils/catchErrors.js'
import * as Icon from 'react-bootstrap-icons'; import * as Icon from 'react-bootstrap-icons';
import axios from "axios"; import axios from "axios";
const INIT_PAGE = {
title: '',
url: '',
}
function Search(props) { function Search(props) {
const endPage = 10; const endPage = 10;
const [state, setState] = useState(false); const [state, setState] = useState(false);
...@@ -15,6 +21,9 @@ function Search(props) { ...@@ -15,6 +21,9 @@ function Search(props) {
const [search, setSearch] = useState(props.location.state.id); const [search, setSearch] = useState(props.location.state.id);
const [mobile, setMobile] = useState(); const [mobile, setMobile] = useState();
const [show, setShow] = useState(false); const [show, setShow] = useState(false);
const [page, setPage] = useState(INIT_PAGE)
const [success, setSuccess] = useState(false)
const [error, setError] = useState('')
const handleClose = () => setShow(false); const handleClose = () => setShow(false);
const handleShow = () => setShow(true); const handleShow = () => setShow(true);
...@@ -69,16 +78,23 @@ function Search(props) { ...@@ -69,16 +78,23 @@ function Search(props) {
setSearch(e.target.value); setSearch(e.target.value);
} }
const handleSubmit = (e) => { async function handleSubmit(e){
setState(true); setState(true); //버튼이 눌려서 handlesubmit이될때 setState값이 true로 바뀐다
try { //respons 서버에 post로 요청하여 데이터를 받아온다
const response = await axios.post('/api/users/bookmark', page)
setSuccess(true)
} catch (error) {
console.log(error)
catchErrors(error, setError)
}
} }
function paginate(items, pageNumber, itemNumber) { function paginate(items, pageNumber, itemNumber) {
const page = []; const page = []; //페이지를 빈배열로 설정
const startIndex = (pageNumber - 1) * itemNumber const startIndex = (pageNumber - 1) * itemNumber // 처음인덱스 값이 페이지넘버 -1 * 아이템 넘버로
for (var i = 0; i < itemNumber; i++) { for (var i = 0; i < itemNumber; i++) {
page.push(items[(startIndex + i)]) page.push(items[(startIndex + i)])
} }
return page return page
} }
...@@ -108,7 +124,7 @@ function Search(props) { ...@@ -108,7 +124,7 @@ function Search(props) {
return ( return (
<Col key={index} md={6} > <Col key={index} md={6} >
<Card align="center" border="info" style={{ margin: "3%" }}> <Card align="center" border="info" style={{ margin: "3%" }}>
<Button variant="outline-info" style={{ marginLeft: "55vh" }} type='submit'><Icon.BookmarkStar size={30} /></Button> <Button onSubmit={handleSubmit} variant="outline-info" style={{ marginLeft: "55vh" }} type='submit'><Icon.BookmarkStar size={30} /></Button>
<Card.Title style={{ margin: "3%", fontSize: '200%', fontWeight: 'bold' }}>{place.name} <Card.Title style={{ margin: "3%", fontSize: '200%', fontWeight: 'bold' }}>{place.name}
</Card.Title> </Card.Title>
<Card.Img variant="top" style={{ padding: "5%", width: "100%", height: "340px" }} src={place.img} /> <Card.Img variant="top" style={{ padding: "5%", width: "100%", height: "340px" }} src={place.img} />
...@@ -146,4 +162,4 @@ export default Search ...@@ -146,4 +162,4 @@ export default Search
// const bookmarksave = async (req, res) => { // const bookmarksave = async (req, res) => {
// const {userId, bookmarkId} = req.body // const {userId, bookmarkId} = req.body
// let bookmark = await Bookmark.findOne({bookmarkId:bookmarkId}).select('user') // let bookmark = await Bookmark.findOne({bookmarkId:bookmarkId}).select('user')
// } // }
\ No newline at end of file
...@@ -8,6 +8,7 @@ import reportWebVitals from './reportWebVitals'; ...@@ -8,6 +8,7 @@ import reportWebVitals from './reportWebVitals';
import Signup from './Components/Signup' import Signup from './Components/Signup'
import Login from './Components/Login' import Login from './Components/Login'
import PrivateRoute from "./Components/PrivateRoute"; import PrivateRoute from "./Components/PrivateRoute";
import axios from 'axios'
import Bookmark from "./Bookmark" import Bookmark from "./Bookmark"
import { import {
BrowserRouter as Router, BrowserRouter as Router,
...@@ -16,9 +17,9 @@ import { ...@@ -16,9 +17,9 @@ import {
Redirect, Redirect,
} from "react-router-dom"; } from "react-router-dom";
// axios.defaults.validateStatus = function (status) { axios.defaults.validateStatus = function (status) {
// return status < 500; // default return status < 500; // default
// } }
ReactDOM.render( ReactDOM.render(
<React.StrictMode> <React.StrictMode>
......
...@@ -7,11 +7,11 @@ export function handleLogin(userId) { ...@@ -7,11 +7,11 @@ export function handleLogin(userId) {
export async function handleLogout() { export async function handleLogout() {
localStorage.removeItem('loginStatus') localStorage.removeItem('loginStatus')
await axios.get('/api/auth/logout') await axios.get('/api/auth/logout')
window.location.href='/' window.location.href='/' //경로 지정
} }
//유저가 로그인 했는 지 확인하는 함수
export function isAuthenticated() { export function isAuthenticated() {
const userId = localStorage.getItem('loginStatus') const userId = localStorage.getItem('loginStatus') //유저아이디를 로컬스토리지에서 가져와서 저장
if (userId) { if (userId) {
return userId return userId
}else{ }else{
......
This diff is collapsed.
...@@ -5,7 +5,7 @@ import axios from 'axios'; ...@@ -5,7 +5,7 @@ import axios from 'axios';
import { time } from 'console'; import { time } from 'console';
const searchPlace = async (req, res) => { const searchPlace = async (req, res) => {
//url 설정
const url = "https://search.naver.com/search.naver?sm=tab_hty.top&where=nexearch&query=" + encodeURI(req.params.search) const url = "https://search.naver.com/search.naver?sm=tab_hty.top&where=nexearch&query=" + encodeURI(req.params.search)
const editUrl = /(http(s)?:\/\/)([a-z0-9\w]+\.*)+[a-z0-9]{2,4}/gi const editUrl = /(http(s)?:\/\/)([a-z0-9\w]+\.*)+[a-z0-9]{2,4}/gi
axios.get(url) axios.get(url)
......
import Review from '../models/Review.js' import Review from '../models/Review.js'
import cheerio from "cheerio"; import cheerio from "cheerio";
// import iconv from 'iconv'
import fs from 'fs' import fs from 'fs'
import axios from 'axios'; import axios from 'axios';
// const Iconv = iconv.Iconv // const Iconv = iconv.Iconv
const search = async (req, res, next) => { const search = async (req, res, next) => {
//**************************구글 크롤링 할 때************************/
try { try {
let reviews = [] let reviews = []
let content = [] let content = []
Review.find()
const url = "https://www.google.com/search?q=" + encodeURI(req.params.search) + "+site%3Atistory.com&page_no=1" const url = "https://www.google.com/search?q=" + encodeURI(req.params.search) + "+site%3Atistory.com&page_no=1"
const response1 = await axios.get(url) const response1 = await axios.get(url)
fs.writeFileSync("googleSearch", response1.data, { encoding: 'utf-8' })
// console.log(response1.data) // console.log(response1.data)
const $1 = cheerio.load(response1.data); const $1 = cheerio.load(response1.data);
$1('.kCrYT').each(async function (i) { $1('.kCrYT').each(async function (i) {
...@@ -27,20 +32,19 @@ const search = async (req, res, next) => { ...@@ -27,20 +32,19 @@ const search = async (req, res, next) => {
reviews = reviews.filter(e => e) reviews = reviews.filter(e => e)
} }
}) })
let promiseReview = await Promise.all(content) const promiseReview = await Promise.all(content)
promiseReview = promiseReview.filter(e => typeof (e) === 'string')
reviews.forEach(async (review, i) => { reviews.forEach(async (review, i) => {
review["content"] = promiseReview[i] review["content"] = promiseReview[i]
const reviews = new Review(review).save()
}) })
res.send(reviews) res.send(reviews)
} catch (error) { } catch (error) {
console.log(error) // console.log(error)
res.send(error) res.send(error)
} }
} }
//***************네이버 크롤링 할 때 ********************* */ //***************네이버 크롤링 할 때 ********************* */
// try { // try {
// let reviews = [] // let reviews = []
...@@ -60,19 +64,16 @@ const search = async (req, res, next) => { ...@@ -60,19 +64,16 @@ const search = async (req, res, next) => {
// } // }
const getReview = async (link) => { const getReview = async (link) => {
let content = '없음'
if (link) { if (link) {
let content = '없음'
const res = await axios.get(link) const res = await axios.get(link)
const $2 = cheerio.load(res.data); const $2 = cheerio.load(res.data); // cheerio 의미
if ($2('.tt_article_useless_p_margin').text()) { if ($2('.tt_article_useless_p_margin').text()) {
content = $2('.tt_article_useless_p_margin').text() content = $2('.tt_article_useless_p_margin').text()
} }
return content
} }
return content
} }
const find = (res,req,next) => { export default { search, getReview }
Review.find({address: })
}
export default { search, find }
...@@ -2,6 +2,7 @@ import User from "../models/User.js" ...@@ -2,6 +2,7 @@ import User from "../models/User.js"
import isLength from 'validator/lib/isLength.js' import isLength from 'validator/lib/isLength.js'
import isEmail from "validator/lib/isEmail.js" import isEmail from "validator/lib/isEmail.js"
import bcrypt from "bcryptjs"; import bcrypt from "bcryptjs";
const reviews = ("../models/Review.js");
const signup = async (req, res) => { const signup = async (req, res) => {
const { name, email, password } = req.body //구조분해해서 하나씩 const { name, email, password } = req.body //구조분해해서 하나씩
...@@ -33,7 +34,7 @@ const signup = async (req, res) => { ...@@ -33,7 +34,7 @@ const signup = async (req, res) => {
} }
const userById = async (req, res, next, id) => { const userById = async (req, res, next, id) => {
try { try {
const user = await User.findById(id) const user = await User.findById(id)
if (!user) { if (!user) {
res.status(404).send('사용자를 찾을 수 없습니다') res.status(404).send('사용자를 찾을 수 없습니다')
...@@ -46,18 +47,49 @@ const userById = async (req, res, next, id) => { ...@@ -46,18 +47,49 @@ const userById = async (req, res, next, id) => {
} }
} }
const bookMark = async (req, res) => { // const bookMark = async (req, res) => {
const {title, url} = req.body // const {title, url} = req.body
console.log(title, url) // console.log(title, url)
try { // try {
let bookmark = [] // let bookmark = []
const newBookmark = await new User ({ // const newBookmark = await new User ({
bookmark, // bookmark,
}).save() // }).save()
} catch (error) { // } catch (error) {
console.log(error) // console.log(error)
res.status(500).send('사용자 아이디 검색 실패') // res.status(500).send('사용자 아이디 검색 실패')
} // }
} // }
const bookMark = async(req, res, next) => {
const { title, link, content } = req.body; // 비구조화 할당
console.log(req.body);
let bookmark = []
const newBookmark = await new Bookmark ({
}).save()
var reviewModel = new reviews();
reviewModel.title = title;
reviewModel.content = content;
reviewModel.link = link;
reviewModel
.save()
.then(newReview => {
console.log("Create 완료");
res.status(200).json({
message: "Create success",
data: {
review: newReview
}
});
})
.catch(err => {
res.status(500).json({
message: err
});
});
};
export default { signup, userById } export default { signup, userById, bookMark }
\ No newline at end of file \ No newline at end of file
...@@ -30,4 +30,4 @@ const ReviewSchema = new mongoose.Schema({ ...@@ -30,4 +30,4 @@ const ReviewSchema = new mongoose.Schema({
timestamps: true timestamps: true
}) })
export default mongoose.models.Review || mongoose.model('Review', ReviewSchema) export default mongoose.models.Review || mongoose.model('Review', ReviewSchema)
\ No newline at end of file
...@@ -2,7 +2,7 @@ import express from "express" ...@@ -2,7 +2,7 @@ import express from "express"
import authCtrl from "../controllers/auth.controller.js" import authCtrl from "../controllers/auth.controller.js"
const router = express.Router() const router = express.Router()
//경로 설정?
router.route('/api/auth/login') router.route('/api/auth/login')
.post(authCtrl.login) .post(authCtrl.login)
......
...@@ -8,4 +8,14 @@ router.route('/api/users/signup') ...@@ -8,4 +8,14 @@ router.route('/api/users/signup')
router.param('userId', userCtrl.userById) router.param('userId', userCtrl.userById)
router.get('/admin/:_id', verifyToken, function (req, res, next) {
console.log('/reserves/admin get req.params', req.params)
Reserve.find({ approve: false }).populate('user').exec(function (err, reserve) {
if (err) return res.status(500).json({ error: err });
console.log('reserve list', reserve)
res.status(201).json(reserve);
})
});
export default router export default router
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment