• 로그인
  • 장바구니에 상품이 없습니다.

home2 게시판 React 게시판 POST 요청

POST 요청

  • 이 주제에는 1개 답변, 2명 참여가 있으며 codingapple2 년 전에 전에 마지막으로 업데이트했습니다.
2 글 보임 - 1 에서 2 까지 (총 2 중에서)
  • 글쓴이
  • #94312

    쥬니
    참가자
    안녕하세요. 리액트 강의의 끝을 바라보고있는 수강생입니다. 프로젝트를 진행하면서 궁금한점이 생겨 질문드립니다.
    마이페이지의 회원정보를 수정하는 부분을 진행하고있습니다. POST요청 시 프로필사진, 닉네임, 자기소개 3가지데이터가 body값으로 들어가야하는데, 이 중 일부만 수정하면 수정이안되고, 3개를 전부 수정했을때만 수정이 됩니다. 
    기존의 데이터에서 일부만 수정해서 보내면 400에러(request에러)가뜹니다. 그리고 수정하지않은 나머지 데이터는 기존의 데이터값을 그대로 담아서 전달합니다. 
     스크린샷 2023-08-11 011143
    물론 PATCH, PUT사용해야 한다는 것을 깨닫고, 서버분과 같이 그 방향으로 수정하긴했습니다. 그렇지만 개인적으로 POST요청시에는 왜 그런오류가 생기는지 잘모르겠습니다.
    이게 클라이언트 요청에는 문제가 없어보이는데 서버측 코드 오류일 가능성이 큰가요? 아니면 POST자체가 그런 특성을 가진건가요..
    import './editprofile.css';
    import axios from "axios";
    function Editprofile(props) {
        let [inputCount, setInputCount] = useState(0);
        const [selectedImage, setSelectedImage] = useState(null);
        const [useDefaultImage, setUseDefaultImage] = useState(true);
        const [defaultImageurl, setDefaultImageurl] = useState('../img/profile.png');
        const countCharacters = (str) => {
            const regex = /[\x00-\x7F]|[\u3131-\uD79D]|./g; // ASCII 문자, 한글 문자, 그 외의 모든 문자
            const matches = str.match(regex);
            return matches ? matches.length : 0;
        };
        const onTextareaHandler = (e) => {
            setInfo((prevInfo) => ({
                ...prevInfo,
                aboutMe: e.target.value
            }));
            const inputValue = e.target.value;
            const characterCount = countCharacters(inputValue);
            setInputCount(characterCount);
        };
        const onImageSelectHandler = (e) => {
            e.preventDefault();
            if(e.target.files){
                const uploadFile = e.target.files[0]
                console.log(uploadFile)
                setSelectedImage(uploadFile);
                setUseDefaultImage(false);
            }
        };
        
        let [Info, setInfo] = useState({});
        useEffect(() => {
            //localStorage에서 access token을 가져옵니다.
            const accessToken = 'Bearer 사용자토큰';
            // access token을 인증 헤더에 설정합니다.
            axios.defaults.headers.common["Authorization"] = accessToken;
            axios.get('/mypage/profile')
                .then((response) => {
                    // result 객체를 petInfo 상태로 설정합니다.
                    console.log(response.data.result);
                    setInfo(response.data.result);
                    console.log(Info);
                    setDefaultImageurl(response.data.result.imageUrls);
                }).catch((error) => {
                    // 에러가 발생하면, 해당 에러 객체가 catch() 메서드의 매개변수인 error에 자동으로 전달됩니다.
                    console.error('Error fetching pet information:', error);
                });
        }, []); 
        
        const updateProfile = async () => {
            console.log('Before updating profile:', Info);
        
            const formData = new FormData();
            formData.append('nickname', Info.nickname);
            formData.append('aboutMe', Info.aboutMe);
        
            if (!useDefaultImage) {
                // Create a Blob from the selected image file
                const imageBlob = new Blob([selectedImage], { type: selectedImage.type });
                // Append the Blob to the FormData with the desired field name ('multipartFile')
                formData.append('multipartFile', imageBlob);//selectedImage.name
            }
            let entries = formData.entries();
            for (const pair of entries) {
                console.log(pair[0],pair[1]);
            }
        
            try {
                const response = await axios.post('/mypage/profile', formData);
                console.log('Profile updated successfully:', response.data.result);
                props.navigate('/mypage/profile');
            } catch (error) {
                console.error('Error updating profile:', error);
            }
        };
    
        return (
            <div className='detail'>
                <h4>프로필 수정</h4>
                <div className='detail_1'>
                    <div className='profile'>
                        <div className="profile-picture">
                        < img src={useDefaultImage || !selectedImage ? defaultImageurl : URL.createObjectURL(selectedImage)} alt="프로필 사진" />
                        </div>
                        <div className="button-container">
                            <label htmlFor="choose-profile">사진 수정</label>
                            <input
                                type="file"
                                id="choose-profile"
                                name="profilePicture"
                                accept="image/*"
                                onChange={onImageSelectHandler}
                                style={{ display: "none" }}
                            />
                            <button className="profile-edit-button2" onClick={() => setUseDefaultImage(true)}>
                                기본 이미지
                            </button>
                        </div>
                    </div>
                    <div className='profile_content'>
                        <div className='nickname'>
                            <label for="nickname">닉네임</label>
                            <input type="text" id="nickname" name="nickname" value={Info.nickname} placeholder="닉네임을 입력하세요"
                                onChange={(e) => setInfo((prevInfo) => ({ ...prevInfo, nickname: e.target.value }))}
                            />
                        </div>
                        <div className='introduction'>
                            <label for="introduction">자기소개</label>
                            <textarea id="introduction" name="introduction" value={Info.aboutMe} placeholder="자기소개를 입력하세요"
                                onChange={onTextareaHandler} maxLength="1000"
                            ></textarea>
                        </div>
                        <div className='p-wrapper'>
                            <p>
                                <span>{inputCount}</span>
                                <span>/1000 자</span>
                            </p>
                        </div>
                        <div class="edit-button-container">
                            <button className="edit-profile-button" onClick={updateProfile}>수정하기</button>
                        </div>
                        {console.log(Info)}
                    </div>
                </div>
            </div>
        )
    }
    export default Editprofile;
    #94322

    codingapple
    키 마스터
    리액트에서 맘대로 요청날릴 순 없습니다 
    서버개발자가 만든 url과 method로 요청안날리면 4xx 에러 뜹니다 
    
    
2 글 보임 - 1 에서 2 까지 (총 2 중에서)
  • 답변은 로그인 후 가능합니다.

About

현재 월 700명 신규수강중입니다.

  (09:00~20:00) 빠른 상담은 카톡 플러스친구 코딩애플 (링크)
  admin@codingapple.com
  이용약관, 개인정보처리방침
ⓒ Codingapple, 강의 예제, 영상 복제 금지
top

© Codingapple, All rights reserved. 슈퍼로켓 에듀케이션 / 서울특별시 강동구 고덕로 19길 30 / 사업자등록번호 : 212-26-14752 온라인 교육학원업 / 통신판매업신고번호 : 제 2017-서울강동-0002 호 / 개인정보관리자 : 박종흠