Commit a0df9bdf authored by Lee SeoYeon's avatar Lee SeoYeon
Browse files

merge

parent ff493dfa
import React, { useState, useEffect } from 'react';
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 } from 'react-bootstrap';
import Paginations from '../Components/Paginations';
import axios from 'axios';
import queryString from 'query-string'
function Search(props) {
const endPage = 10;
const [state, setState] = useState(false);
const [index, setIndex] = useState(1);
const [showSet, setShowSet] = useState([false, false, false, false]);
const [search, setSearch] = useState(queryString.parse(props.location.search).keyword);
const [mobile, setMobile] = useState();
// const [place, setPlace] = useState([{ name: "", category: "", address: "" }])
// const [imgUrl, setImgUrl] = useState([])
const [association, setAssociation] = useState([])
const [pagePlace, setPagePlace] = useState([])
// console.log("search###############", search)
// const getPlace = () => {
// axios.get(`/api/search/places?keyword=${search}`)
// .then(res => {
// console.log("places=", res.data)
// // setPlace(res.data)
// })
// .catch(err => {
// console.log('search.places 에러 발생', err)
// })
// }
// const getImg = () => {
// axios.get(`/api/search/imges?keyword=${search}`)
// .then(res => {
// console.log("images=", res.data)
// // setImgUrl(res.data)
// })
// .catch(err => {
// console.log('search.images 에러 발생', err)
// })
// }
const getAssociation = () => {
axios.get(`/api/search/association?keyword=${search}`)
.then(res => {
console.log("Associations = ", res.data)
setAssociation(res.data)
})
.catch(err => {
console.log("search.associations 에러 발생", err)
})
}
useEffect(() => {
// getPlace()
// getImg()
getAssociation()
if (window.innerWidth < 960) {
setMobile(true)
} else {
setMobile(false)
}
}, []);
useEffect(() => {
// getImg()
// getAssociation()
setPagePlace(paginate(association, index, association.length))
}, [association])
useEffect(() => {
// getPlace()
// getImg()
getAssociation()
if (state) {
props.history.push('/search?keyword=' + search)
setState(false)
console.log("search야", search)
}
}, [state])
const places = [{
name: "한라산",
address: "제주 서귀포시 토평동 산15-1",
img: "https://upload.wikimedia.org/wikipedia/commons/thumb/e/eb/KOCIS_Halla_Mountain_in_Jeju-do_%286387785543%29.jpg/269px-KOCIS_Halla_Mountain_in_Jeju-do_%286387785543%29.jpg?size=200x200",
}, {
name: "성산일출봉(sungsan)",
address: "제주 서귀포시 성산읍 성산리 1",
img: "https://www.jeju.go.kr/pub/site/geopark/images/sub/sub03/02%EC%A7%80%EC%A7%88%EB%A7%88%EC%9D%84%EC%9D%B4%EC%95%BC%EA%B8%B0/%EC%A7%80%EC%A7%88%EB%A7%88%EC%9D%84/%EC%A7%80%EC%A7%88%EB%A7%88%EC%9D%84_%EC%84%B1%EC%82%B0%EC%9D%BC%EC%B6%9C%EB%B4%89/1412402261.jpg?400/400",
}, {
name: "해녀의 집(haenyeo)",
address: "제주 서귀포시 성산읍 한도로 141-13지번오조리 3 오조해녀의집",
img: "https://mblogthumb-phinf.pstatic.net/MjAxNjExMTdfMTc0/MDAxNDc5MzU3ODU0ODQy.KZYXCjzsXT3rCsE4HXBfxyCg2buvluBvN_7NxVp7BSwg.loJc89d8JjGXdNCn-4yMd7aMWPjfrZn21TI9Hyzemkog.JPEG.icocam11/20161010_100205.jpg?type=w800",
}, {
name: "오설록 티 뮤지엄(osulloc)",
address: "제주 서귀포시 안덕면 신화역사로 15 오설록지번서광리 1235-1 오설록",
img: "https://cdnweb01.wikitree.co.kr/webdata/editor/202007/01/img_20200701143323_2ced7627.webp",
}, {
name: "오설록 티 뮤지엄(osulloc)",
address: "제주 서귀포시 안덕면 신화역사로 15 오설록지번서광리 1235-1 오설록",
img: "https://upload.wikimedia.org/wikipedia/commons/thumb/e/eb/KOCIS_Halla_Mountain_in_Jeju-do_%286387785543%29.jpg/269px-KOCIS_Halla_Mountain_in_Jeju-do_%286387785543%29.jpg",
}]
if (state !== false) {
// console.log(queryString.parse(props.location.search))
// = {keyword:search}
// return <Redirect to={{
// pathname: `/search?keyword=${search}`,
// state: { id: search },
// }} />;
// history.pushState(null, null, "?"+queryParams.toString());
// return <Redirect to={`/search?keyword=${search}`} />;
}
const handlePage = (num) => {
setIndex(num);
}
const handleChange = (e) => {
setSearch(e.target.value);
}
const handleSubmit = (e) => {
e.preventDefault()
setState(true);
}
function paginate(items, pageNumber, itemNumber) {
const page = [];
const startIndex = (pageNumber - 1) * itemNumber
for (var i = 0; i < itemNumber; i++) {
page.push(items[(startIndex + i)])
}
return page
}
let time = new Date()
return (
<Container >
<Link to="/" className="d-flex justify-content-center"><Image src={ohuh} /></Link>
<Row className="mb-2" className="d-flex justify-content-center">
<Form style={{ width: "90vw" }} onSubmit={handleSubmit}>
<InputGroup size="lg">
<FormControl
placeholder="검색어를 입력하세요."
value={search}
aria-label="Large"
aria-describedby="inputGroup-sizing-sm"
onChange={handleChange}
/>
<InputGroup.Append>
<Button type="submit" variant="outline-secondary" >검색</Button>
</InputGroup.Append>
</InputGroup>
</Form>
</Row>
{time.toLocaleString()}
<Row className="d-flex flex-wrap">
{pagePlace.map((place, index) => {
return (
<Col key={index} md={6} >
<Card align="center" border="info" style={{ margin: "3%" }}>
<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} />
<Card.Body >
<Card.Text style={{ overflow: 'auto', fontSize: '25px', width: '100%', height: "80px" }} >
{place.address} </Card.Text>
<Button variant="primary" onClick={() => {
const showArr = [false, false, false, false]
showArr[index] = true
setShowSet(showArr)
}}>{place.name} 자세히 살펴보기</Button>
<Place place={place} index={index} show={showSet[index]} onHide={() => setShowSet([false, false, false, false])} />
</Card.Body>
</Card>
</Col>
)
})}
</Row>
<Row className="mt-2 d-flex justify-content-center">
<Paginations index={index} endPage={endPage} handlePage={handlePage}></Paginations>
</Row>
</Container>
);
}
export default Search;
......@@ -2,13 +2,13 @@ import Places from '../models/Place.js'
import cheerio from 'cheerio'
// import fs from 'fs'
import axios from 'axios';
import { nextTick } from 'process';
const searchPlace = async (req, res) => {
const searchPlace = async (req, res, next,) => {
let DuplicateCheckPlace = await Places.findOne({ name: req.query.keyword })
req.places = DuplicateCheckPlace
if (DuplicateCheckPlace) {
res.send(DuplicateCheckPlace)
console.log("11111111111111111111111Place################ 기존플레이스줄력중")
}
else {
......@@ -23,70 +23,115 @@ const searchPlace = async (req, res) => {
let places = {}
$1('.ct_box_area').each(function (i) {
places[i] = { name: $1('.biz_name').text(), category: $1('.category').text(), address: $1('.addr').text() }
places={
name: $1('.biz_name').text(), category: $1('.category').text(), address: $1('.addr').text()
}
})
// 값이 비어있거나 에러가 생겼을 때를 대비해 try catch를 해야함
const newPlaces = await new Places(places[0]
).save()
res.send(places)
// const newPlaces = await new Places(places[0]
// ).save()
// res.send(places)
req.places = places[0]
console.log("62168748172", req.places)
})
}
next()
}
const searchImg = async (req, res) => {
const searchImg = async (req, res, next) => {
let DuplicateCheckImg = await Places.findOne({ name: req.query.keyword })
console.log("d213532513212osfnlagm2214124", req.places)
if (DuplicateCheckImg) {
if (DuplicateCheckImg.img !== "https://t1.daumcdn.net/thumb/R600x0/?fname=http%3A%2F%2Ft1.daumcdn.net%2Fqna%2Fimage%2F4b035cdf8372d67108f7e8d339660479dfb41bbd") {
res.send(DuplicateCheckImg)
if (req.places.img) {
console.log("333333333333333333333333333IMG@@@@@@@@@@@@@@@@@@@ 기존이미지줄력중")
}
else if (DuplicateCheckImg.img === "https://t1.daumcdn.net/thumb/R600x0/?fname=http%3A%2F%2Ft1.daumcdn.net%2Fqna%2Fimage%2F4b035cdf8372d67108f7e8d339660479dfb41bbd") {
console.log("4444444444444444444444444444444444444444444444444")
req.places.times.push(new Date().toLocaleString())
console.log("세이브 전 111111111111111111", req.places)
const newPlaces = await new Places(req.places).save()
next()
} else {
const imgUrl = "https://www.google.com/search?q=" + encodeURI(req.query.keyword) + "+site:tistory.com/&sxsrf=ALeKk023Dv08KQDodRmpB5222lQuzw2Vaw:1610612821100&source=lnms&tbm=isch"
axios.get(imgUrl)
.then(async (response) => {
console.log("4444444444444444444444444444444444444444444444444새로운 이미지 출력중")
const html = response.data
let name = req.query.keyword
let $1 = cheerio.load(html);
let images = $1('.RAyV4b').find('img').attr('src')
req.places.img = images
//사진만 업데이트
let Place = await Places.findOne({ name: req.query.keyword })
Place.times.push(new Date().toLocaleString())
await Places.updateOne({ name: req.query.keyword }, { img: images, times: Place.times })
// let Place2 = await Places.findOne({ name: req.query.keyword })
req.places.times.push(new Date().toLocaleString())
// await Places.updateOne({ name: req.query.keyword }, { img: images, times: Place2.times })
// res.send(images)
console.log("세이브 전 222222222222222", req.places)
const newPlaces = await new Places(req.places).save()
next()
res.send(images)
})
} else {
console.log("IMG에러")
}
}
}
}
// if (DuplicateCheckImg !== "https://t1.daumcdn.net/thumb/R600x0/?fname=http%3A%2F%2Ft1.daumcdn.net%2Fqna%2Fimage%2F4b035cdf8372d67108f7e8d339660479dfb41bbd") {
// console.log("333333333333333333333333333IMG@@@@@@@@@@@@@@@@@@@ 기존이미지줄력중")
// }
// else if (DuplicateCheckImg === "https://t1.daumcdn.net/thumb/R600x0/?fname=http%3A%2F%2Ft1.daumcdn.net%2Fqna%2Fimage%2F4b035cdf8372d67108f7e8d339660479dfb41bbd") {
// console.log("4444444444444444444444444444444444444444444444444")
// const imgUrl = "https://www.google.com/search?q=" + encodeURI(req.query.keyword) + "+site:tistory.com/&sxsrf=ALeKk023Dv08KQDodRmpB5222lQuzw2Vaw:1610612821100&source=lnms&tbm=isch"
// axios.get(imgUrl)
// .then(async (response) => {
// const html = response.data
// let name = req.query.keyword
// let $1 = cheerio.load(html);
// let images = $1('.RAyV4b').find('img').attr('src')
// req.places.img = images
// //사진만 업데이트
// // let Place2 = await Places.findOne({ name: req.query.keyword })
// req.places.times.push(new Date().toLocaleString())
// // await Places.updateOne({ name: req.query.keyword }, { img: images, times: Place2.times })
// // res.send(images)
// console.log("세이브 전 111111111111111111", req.places)
// const newPlaces = await new Places(req.places).save()
// next()
// })
// } else {
// console.log("IMG에러")
// }
// req.places.times.push(new Date().toLocaleString())
// console.log("세이브 전222222222222222222222")
// next()
// }
//맨 처음 검색하는 지역의 관광지의 경우 association을 받아올 수 없다.
const searchAssociation = async (req, res) => {
let Place = await Places.findOne({ name: req.query.keyword })
// let Place3 = await Places.findOne({ name: req.query.keyword })
let Place3 = req.places.address
// if (!Place) {
// res.send([])
// }
if (!Place) {
res.status(404).send({ error: "Place.address is null" })
if (!Place3) {
console.log("asdfasdfasdf222222222222222222dsaf2222222222214123q5", Place3)
res.send({ error: "Place.address is null" })
}
else {
let addresse = Place.address.split(' ')[0]
let addresse = Place3.split(' ')[0]
let AssociationsId = []
let addressPlaces = new RegExp(`${addresse}`)
console.log("여기보세요", addressPlaces)
let responsePlaces = await Places.find({ address: addressPlaces })
// const newPlaces = await new Places(places[0]).save()
res.send(responsePlaces)
}
// responsePlaces.map(Association => {
......
......@@ -3,13 +3,14 @@ import place from '../controllers/place.controller.js'
const router = express.Router()
router.route('/api/search/imges')
.get(place.searchImg)
// router.route('/api/search/places')
// .get(place.searchPlace, place.searchImg, place.searchAssociation)
// router.route('/api/search/imges')
// .get(place.searchImg)
router.route('/api/search/places')
.get(place.searchPlace)
router.route('/api/search/association')
.get(place.searchAssociation)
.get(place.searchPlace, place.searchImg, place.searchAssociation)
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