-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathboardNew.js
235 lines (216 loc) · 6.17 KB
/
boardNew.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
import React, { useState } from "react";
import {
View,
Text,
TextInput,
TouchableOpacity,
StyleSheet,
Alert,
ScrollView,
Keyboard,
TouchableWithoutFeedback,
KeyboardAvoidingView,
Platform,
} from "react-native";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { useNavigation } from "@react-navigation/native";
const BoardNew = () => {
const [title, setTitle] = useState("");
const [content, setContent] = useState("");
const [selectedTag, setSelectedTag] = useState("#정보");
const navigation = useNavigation();
const handleKeyboardSubmit = () => {
if (content.trim()) {
handleSubmit();
}
};
const handleSubmit = async () => {
if (!title.trim() || !content.trim()) {
Alert.alert("알림", "제목과 내용을 모두 입력해주세요.");
return;
}
try {
// AsyncStorage에서 JWT 토큰과 닉네임 가져오기
const jwtToken = await AsyncStorage.getItem("jwtToken");
const userNickname = await AsyncStorage.getItem("userNickname");
console.log("저장된 JWT 토큰:", jwtToken);
console.log("사용자 닉네임:", userNickname);
if (!jwtToken || !userNickname) {
Alert.alert("인증 오류", "로그인이 필요합니다.");
navigation.navigate("KakaoLogin");
return;
}
const baseUrl =
process.env.SERVER_URL || "http://192.168.61.45:8080/api/posts";
const postData = {
title: title.trim(),
content: content.trim(),
tags: [selectedTag.replace("#", "")],
nickname: userNickname,
memberId: await AsyncStorage.getItem("userId"),
};
console.log("전송할 게시글 데이터:", postData);
const response = await fetch(baseUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${jwtToken}`,
Accept: "application/json",
},
body: JSON.stringify(postData),
});
console.log("서버 응답 상태:", response.status);
const responseText = await response.text();
console.log("서버 응답 텍스트:", responseText);
if (!response.ok) {
if (response.status === 401) {
Alert.alert("인증 만료", "다시 로그인해주세요.");
navigation.navigate("KakaoLogin");
return;
}
throw new Error(`서버 응답 오류: ${response.status}`);
}
// 응답이 비어있지 않은 경우에만 JSON 파싱 시도
if (responseText && responseText.trim()) {
try {
const result = JSON.parse(responseText);
console.log("게시글 등록 성공:", result);
} catch (parseError) {
console.log("JSON 파싱 실패, 하지만 요청은 성공:", responseText);
}
}
// 성공 처리
Alert.alert("성공", "게시글이 등록되었습니다.", [
{
text: "확인",
onPress: () => {
navigation.goBack();
},
},
]);
} catch (error) {
console.error("게시글 등록 에러:", error);
Alert.alert("오류", "게시글 등록에 실패했습니다. 다시 시도해주세요.");
}
};
return (
<KeyboardAvoidingView
behavior={Platform.OS === "ios" ? "padding" : "height"}
style={styles.container}
>
<TouchableWithoutFeedback onPress={Keyboard.dismiss}>
<ScrollView style={styles.innerContainer}>
<View style={styles.tagContainer}>
{["#정보", "#조언", "#나눔"].map((tag) => (
<TouchableOpacity
key={tag}
style={[
styles.tagButton,
selectedTag === tag && styles.selectedTag,
]}
onPress={() => setSelectedTag(tag)}
>
<Text
style={[
styles.tagText,
selectedTag === tag && styles.selectedTagText,
]}
>
{tag}
</Text>
</TouchableOpacity>
))}
</View>
<Text style={styles.title}>제목</Text>
<TextInput
style={styles.titleInput}
value={title}
onChangeText={setTitle}
returnKeyType="next"
/>
<Text style={styles.title}>내용</Text>
<TextInput
style={styles.contentInput}
value={content}
onChangeText={setContent}
multiline
textAlignVertical="top"
returnKeyType="done"
onSubmitEditing={handleKeyboardSubmit}
blurOnSubmit={true}
enablesReturnKeyAutomatically={true}
/>
<TouchableOpacity style={styles.submitButton} onPress={handleSubmit}>
<Text style={styles.submitButtonText}>작성 완료</Text>
</TouchableOpacity>
</ScrollView>
</TouchableWithoutFeedback>
</KeyboardAvoidingView>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 16,
backgroundColor: "#fff",
},
title: {
fontSize: 16,
marginBottom: 8,
},
titleInput: {
height: 40,
borderWidth: 1,
borderColor: "#FFEDAE",
borderWidth: 2,
marginBottom: 30,
fontSize: 16,
borderRadius: 8,
padding: 12,
},
tagContainer: {
flexDirection: "row",
marginBottom: 16,
gap: 8,
},
tagButton: {
paddingHorizontal: 12,
paddingVertical: 6,
marginBottom: 10,
borderRadius: 10,
backgroundColor: "white",
borderWidth: 2,
borderColor: "#FFEDAE",
},
selectedTag: {
backgroundColor: "#FFEDAE",
},
tagText: {
color: "#000",
},
selectedTagText: {
color: "black",
fontWeight: "bold",
},
contentInput: {
flex: 1,
height: 300,
borderWidth: 2,
borderColor: "#FFEDAE",
borderRadius: 8,
marginBottom: 200,
fontSize: 16,
},
submitButton: {
backgroundColor: "#FFEDAE",
padding: 16,
marginBottom: 20,
borderRadius: 8,
alignItems: "center",
},
submitButtonText: {
fontSize: 16,
fontWeight: "bold",
},
});
export default BoardNew;