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 { Alert, Col, Card, Container, Form, Row, Button, Nav, Navbar, ListGroup, Image, Table } from "react-bootstrap"
import axios from "axios"
import catchErrors from './utils/catchErrors.js'
import { Redirect } from 'react-router-dom'
const INIT_PAGE = {
......@@ -11,14 +12,21 @@ const INIT_PAGE = {
function Bookmark() {
const [page, setPage] = useState(INIT_PAGE)
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) {
event.preventDefault()
try {
setError('')
const response = await axios.post('/api/users/', user)
const response = await axios.post('/api/users/bookmark ', page)
console.log(response.data)
console.log(user)
console.log(page)
// setUser(INIT_USER)
setSuccess(true)
} catch (error) {
......
......@@ -9,27 +9,28 @@ import { handleLogin } from '../utils/auth'
const INIT_USER = {
email: '',
password: ''
}
} //초기 유저에 이메일 비밀번호 설정
function Login() {
//const [<상태 값 저장 변수>, <상태 값 갱신 함수>] = useState(<상태 초기 값>);
const [user, setUser] = useState(INIT_USER)
const [disabled, setDisabled] = useState(true)
const [error, setError] = useState('')
const [success, setSuccess] = useState(false)
const [loading, setLoading] = useState(false)
useEffect(() => {
useEffect(() => { //참거짓 판단 값들의 원소들이 element로 들어간다
const isUser = Object.values(user).every(el => Boolean(el))
isUser ? setDisabled(false) : setDisabled(true)
}, [user])
function handleChange(event) {
const {name, value} = event.target
const {name, value} = event.target //{}안에 값을 이벤트.타겟에 지정?한다
setUser({...user, [name]: value})
}
async function handleSubmit(event) {
event.preventDefault()
event.preventDefault() //리셋을 막는다
try {
setLoading(true)
setError('')
......@@ -46,7 +47,7 @@ function Login() {
if (success) {
console.log('success', success)
return <Redirect to= '/'/>
return <Redirect to= '/'/> //성공하면 홈화면으로 간다
}
return (
......
......@@ -4,7 +4,7 @@ import { Modal, Container, Row, Col, Button, Badge, Card, Accordion, Carousel }
function Place(props) {
const [reviews, setReviews] = useState([])
const getReview = () => {
const getReview = () => { //review를 서버에 연결해서
axios.get(`/api/review/${props.search.name}`)
.then(res => {
console.log("place res.data", res.data)
......
import React from 'react'
import { Route, Redirect } from 'react-router-dom'
import { isAuthenticated } from "../utils/auth";
//로그인 했을때 경로 실행하게 한다
function PrivateRoute({path, children}) {
if (isAuthenticated()) {
return (
......
......@@ -8,7 +8,7 @@ const INIT_USER = {
name: '',
email: '',
password: ''
}
} // 초기유저에 이름, 이메일, 비밀번호를 빈배열로 지정한다.
function Signup() {
const [user, setUser] = useState(INIT_USER)
......@@ -20,16 +20,16 @@ function Signup() {
const isUser = Object.values(user).every(el => Boolean(el))
isUser ? setDisabled(false) : setDisabled(true)
}, [user])
//바뀌는것이 있을때 이벤트가 발생하는 함수?
function handleChange(event) {
const {name, value} = event.target
setUser({...user, [name]: value})
}
async function handleSubmit(event) {
event.preventDefault()
event.preventDefault() //submit을 누르면 이벤트가 실행
try {
setError('')
setError('') //post로 경로를 지정해서 서버에서 값을 받는다
const response = await axios.post('/api/users/signup', user)
console.log(response.data)
console.log(user)
......@@ -40,7 +40,7 @@ function Signup() {
catchErrors(error, setError)
}
}
//성공시 알림창이 뜨고 원래 페이지로 돌아간다
if (success) {
alert('회원가입 되었습니다.')
return <Redirect to='/'/>
......
......@@ -3,10 +3,16 @@ import { Link, Redirect } from 'react-router-dom';
import ohuh from './ohuh-sm.PNG';
import Place from './Components/Place';
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 axios from "axios";
const INIT_PAGE = {
title: '',
url: '',
}
function Search(props) {
const endPage = 10;
const [state, setState] = useState(false);
......@@ -15,6 +21,9 @@ function Search(props) {
const [search, setSearch] = useState(props.location.state.id);
const [mobile, setMobile] = useState();
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 handleShow = () => setShow(true);
......@@ -69,13 +78,20 @@ function Search(props) {
setSearch(e.target.value);
}
const handleSubmit = (e) => {
setState(true);
async function handleSubmit(e){
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) {
const page = [];
const startIndex = (pageNumber - 1) * itemNumber
const page = []; //페이지를 빈배열로 설정
const startIndex = (pageNumber - 1) * itemNumber // 처음인덱스 값이 페이지넘버 -1 * 아이템 넘버로
for (var i = 0; i < itemNumber; i++) {
page.push(items[(startIndex + i)])
}
......@@ -108,7 +124,7 @@ function Search(props) {
return (
<Col key={index} md={6} >
<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>
<Card.Img variant="top" style={{ padding: "5%", width: "100%", height: "340px" }} src={place.img} />
......
......@@ -8,6 +8,7 @@ import reportWebVitals from './reportWebVitals';
import Signup from './Components/Signup'
import Login from './Components/Login'
import PrivateRoute from "./Components/PrivateRoute";
import axios from 'axios'
import Bookmark from "./Bookmark"
import {
BrowserRouter as Router,
......@@ -16,9 +17,9 @@ import {
Redirect,
} from "react-router-dom";
// axios.defaults.validateStatus = function (status) {
// return status < 500; // default
// }
axios.defaults.validateStatus = function (status) {
return status < 500; // default
}
ReactDOM.render(
<React.StrictMode>
......
......@@ -7,11 +7,11 @@ export function handleLogin(userId) {
export async function handleLogout() {
localStorage.removeItem('loginStatus')
await axios.get('/api/auth/logout')
window.location.href='/'
window.location.href='/' //경로 지정
}
//유저가 로그인 했는 지 확인하는 함수
export function isAuthenticated() {
const userId = localStorage.getItem('loginStatus')
const userId = localStorage.getItem('loginStatus') //유저아이디를 로컬스토리지에서 가져와서 저장
if (userId) {
return userId
}else{
......
This diff is collapsed.
......@@ -5,7 +5,7 @@ import axios from 'axios';
import { time } from 'console';
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 editUrl = /(http(s)?:\/\/)([a-z0-9\w]+\.*)+[a-z0-9]{2,4}/gi
axios.get(url)
......
import Review from '../models/Review.js'
import cheerio from "cheerio";
// import iconv from 'iconv'
import fs from 'fs'
import axios from 'axios';
// const Iconv = iconv.Iconv
const search = async (req, res, next) => {
//**************************구글 크롤링 할 때************************/
try {
let reviews = []
let content = []
Review.find()
const url = "https://www.google.com/search?q=" + encodeURI(req.params.search) + "+site%3Atistory.com&page_no=1"
const response1 = await axios.get(url)
fs.writeFileSync("googleSearch", response1.data, { encoding: 'utf-8' })
// console.log(response1.data)
const $1 = cheerio.load(response1.data);
$1('.kCrYT').each(async function (i) {
......@@ -27,20 +32,19 @@ const search = async (req, res, next) => {
reviews = reviews.filter(e => e)
}
})
let promiseReview = await Promise.all(content)
promiseReview = promiseReview.filter(e => typeof (e) === 'string')
const promiseReview = await Promise.all(content)
reviews.forEach(async (review, i) => {
review["content"] = promiseReview[i]
const reviews = new Review(review).save()
})
res.send(reviews)
} catch (error) {
console.log(error)
// console.log(error)
res.send(error)
}
}
//***************네이버 크롤링 할 때 ********************* */
// try {
// let reviews = []
......@@ -60,19 +64,16 @@ const search = async (req, res, next) => {
// }
const getReview = async (link) => {
if (link) {
let content = '없음'
if (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()) {
content = $2('.tt_article_useless_p_margin').text()
}
return content
}
return content
}
const find = (res,req,next) => {
Review.find({address: })
export default { search, getReview }
}
export default { search, find }
......@@ -2,6 +2,7 @@ import User from "../models/User.js"
import isLength from 'validator/lib/isLength.js'
import isEmail from "validator/lib/isEmail.js"
import bcrypt from "bcryptjs";
const reviews = ("../models/Review.js");
const signup = async (req, res) => {
const { name, email, password } = req.body //구조분해해서 하나씩
......@@ -46,18 +47,49 @@ const userById = async (req, res, next, id) => {
}
}
const bookMark = async (req, res) => {
const {title, url} = req.body
console.log(title, url)
try {
// const bookMark = async (req, res) => {
// const {title, url} = req.body
// console.log(title, url)
// try {
// let bookmark = []
// const newBookmark = await new User ({
// bookmark,
// }).save()
// } catch (error) {
// console.log(error)
// 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 User ({
bookmark,
const newBookmark = await new Bookmark ({
}).save()
} catch (error) {
console.log(error)
res.status(500).send('사용자 아이디 검색 실패')
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 }
\ No newline at end of file
export default { signup, userById, bookMark }
\ No newline at end of file
......@@ -2,7 +2,7 @@ import express from "express"
import authCtrl from "../controllers/auth.controller.js"
const router = express.Router()
//경로 설정?
router.route('/api/auth/login')
.post(authCtrl.login)
......
......@@ -8,4 +8,14 @@ router.route('/api/users/signup')
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
\ 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