Programming/JavaScript & TypeScript
[NextJS] 외부 주소에서 이미지 가져올 때..
홍열
2022. 9. 7. 08:38
728x90
NextJS에서 외부 주소를 통해서 이미지를 가져올 때, 다음과 같은 오류가 발생한다.
next.config.js에서 이미지 가져올 domain주소를 넣어줘야한다.
아래와 같이 images에 특정 domain을 넣어준다. 이렇게 하고 npm run dev를 다시 해줘야한다.
images:{
domains:['via.placeholder.com']
}
전체 코드
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
experimental: { reactRoot: true },
swcMinify: true,
images:{
domains:['via.placeholder.com']
}
}
module.exports = nextConfig
외부 이미지 가져오는 소스 코드
import HeadInfo from "../components/HeadInfo";
import {GetStaticProps, InferGetStaticPropsType} from "next";
import Image from "next/image";
import {useEffect, useState} from 'react'
import PhotoStyles from '../styles/Photo.module.css'
type Photo = {
albumId:number
id:number
title:string
url:string
thumbnailUrl:string
}
export default function Content({photos}:InferGetStaticPropsType<GetStaticProps>) {
const [data, setData] = useState<Photo[]|null>([])
useEffect(() =>{
console.log({photos})
setData(photos)
}, [])
//썸네일 url에 외부 이미지 주소가 들어있어서 next.config.js에다가 사용될 외부 주소를 넣어야함 CORS랑 비슷함
return (<div>
<HeadInfo title={'Content'}/>
<h1>Photos</h1>
<ul className={PhotoStyles.photos}>
{data!=null && data.map(photo => (
<li key={photo.id}>
<Image src={photo.thumbnailUrl} width={200} height={200}/>
</li>
))}
</ul>
</div>
)
}
export const getStaticProps:GetStaticProps = async (context) => {
const res = await fetch('https://jsonplaceholder.typicode.com/photos?_start=0&_end=10')
const photos = await res.json()
return {
//{posts:posts}나 posts를 하나만 써도 됨....
props:{photos}
}
}