Skip to content

Commit

Permalink
Merge pull request #74 from Steven90411/develop
Browse files Browse the repository at this point in the history
新增文章編輯中tag和導入作者id功能
  • Loading branch information
Steven90411 authored Sep 3, 2024
2 parents 7b1f1c2 + 411c3e3 commit 499501f
Show file tree
Hide file tree
Showing 26 changed files with 441 additions and 61 deletions.
2 changes: 1 addition & 1 deletion frontend/src/Test1.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ const Test1 = () => {
// eslint-disable-next-line react-hooks/rules-of-hooks
useEffect(() => {
const fetchHello = async () => {
const response = await fetch('http://localhost:8080/blog-0.0.1-SNAPSHOT/api/hello');
const response = await fetch('http://localhost:8080/blog/api/hello');
const data = await response.text(); // 使用 text() 获取字符串响应
console.log(data); // 应该会在控制台打印 "Hello, World!"
};
Expand Down
3 changes: 2 additions & 1 deletion frontend/src/components/Header.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,8 @@ const Header = () => {
const token = localStorage.getItem('token');
if (token) {
try {
const response = await fetch('http://localhost:8080/blog/api/protected-endpoint', {
// const response = await fetch('http://niceblog.myvnc.com:8080/blog/api/protected-endpoint', {
const response = await fetch('http://localhost:8080/blog/api/protected-endpoint', {
method: 'GET',
headers: {
'Authorization': `Bearer ${token}`,
Expand Down
1 change: 1 addition & 0 deletions frontend/src/components/ImageUpload.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ function ImageUpload({ id, onClose }) {
formData.append('file', croppedImage, '.jpg');

try {
// const response = await fetch(`http://niceblog.myvnc.com:8080/blog/api/userProfile/upload-image/${id}`, {
const response = await fetch(`http://localhost:8080/blog/api/userProfile/upload-image/${id}`, {
method: 'POST',
body: formData,
Expand Down
4 changes: 3 additions & 1 deletion frontend/src/components/UserProfile.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ const UserProfile = ({ userId }) => {
useEffect(() => {
setLoading(true);

// fetch(`http://niceblog.myvnc.com:8080/blog/api/userProfile/${userId}`)
fetch(`http://localhost:8080/blog/api/userProfile/${userId}`)
.then(response => response.json())
.then(data => {
Expand Down Expand Up @@ -64,7 +65,8 @@ const UserProfile = ({ userId }) => {
const handleSave = (field) => {
setLoading(true);

fetch(`http://localhost:8080/blog/api/userProfile/update-${field}/${userId}`, {
// fetch(`http://niceblog.myvnc.com:8080/blog/api/userProfile/update-${field}/${userId}`, {
fetch(`http://localhost:8080/blog/api/userProfile/update-${field}/${userId}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
Expand Down
89 changes: 57 additions & 32 deletions frontend/src/pages/ArticleEditor.js
Original file line number Diff line number Diff line change
@@ -1,42 +1,68 @@
import React, { useState } from 'react';
import React, { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import articleService from '../services/ArticleService'; // 假設你有一個文章服務
import articleService from '../services/ArticleService';
import tagService from '../services/TagService';
import authService from '../services/AuthService';
import '../styles/pages/ArticleEditor.css';

const ArticleEditor = () => {
const [title, setTitle] = useState('');
const [contentTEXT, setContentTEXT] = useState('');
const [category, setCategory] = useState('');
const navigate = useNavigate();//用於跳轉網址
const { articleId } = useParams(); // 假設用於編輯現有文章
const [tag, setTag] = useState('');
const [allTags, setAllTags] = useState([]);
const [userId, setUserId] = useState('');
const navigate = useNavigate();
const { articleId } = useParams();
const [likes, setLikes] = useState(0);

// 加載文章內容(如果是編輯模式)
React.useEffect(() => {
if (articleId) {
articleService.getArticleById(articleId).then(article => {
setTitle(article.title);
setContentTEXT(article.contentTEXT);
// setCategory(article.category);
});
}
}, [articleId]);
useEffect(() => {
const initialize = async () => {
try {
const user = await authService.getUserInfo();
setUserId(user.id);

const tags = await tagService.getAllTags();
setAllTags(tags);

if (articleId) {
const article = await articleService.getArticleById(articleId);
setTitle(article.title);
setContentTEXT(article.contentTEXT);
setLikes(article.likes);

// 檢查是否當前用戶為文章作者
if (Number(article.authorId) !== Number(user.id)) {
// 處理無權編輯的邏輯
console.log(article.authorId);
console.log(user.id);
alert("你無權編輯此文章");
navigate('/articlesPage');
} else {
const articleTag = await tagService.getArticleTag(articleId);
setTag(articleTag);
}
}
} catch (error) {
console.error('Error during initialization:', error);
navigate('/login'); // 如果無法獲取用戶信息,重定向到登錄頁面
}
};

initialize();
}, [articleId, navigate]);

const handleSubmit = async (e) => {
e.preventDefault();
const articleData = { title, contentTEXT, category };
const articleData = { title, contentTEXT, tag, likes, authorId: userId };

try {
if (articleId) {
// 更新文章 傳入id和內容
console.log("updating... id="+articleId);
await articleService.updateArticle(articleId, articleData);
} else {
// 創建新文章 只傳入內容 id自動生成
console.log("creating...")
await articleService.createArticle(articleData);
}
alert("文章提交成功! 將返回文章列表");
navigate('/articlesPage'); // 成功後跳轉
navigate('/articlesPage');
} catch (error) {
alert("文章提交失敗! 請稍後再嘗試");
console.error('文章提交失敗:', error);
Expand All @@ -62,21 +88,20 @@ const ArticleEditor = () => {
/>
</div>
<div className="form-group">
<label htmlFor="category">分類:</label>
<label htmlFor="tag">分類:</label>
<select
id="category"
name="category"
value={category}
onChange={(e) => setCategory(e.target.value)}
id="tag"
name="tag"
value={tag}
onChange={(e) => setTag(e.target.value)}
required
>
<option value="">請選擇分類</option>
<option value="財金">財金</option>
<option value="政治">政治</option>
<option value="體育">體育</option>
<option value="國際">國際</option>
<option value="美食">美食</option>
<option value="遊戲">遊戲</option>
{allTags.map((tag) => (
<option key={tag.tag_id} value={tag.tag_id}>
{tag.name}
</option>
))}
</select>
</div>
<div className="form-group">
Expand Down
1 change: 0 additions & 1 deletion frontend/src/pages/ForgotPasswordPage.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ const ForgotPasswordPage = () => {

try {
const response = await fetch('http://localhost:8080/blog/ac/forgot-password', {
//const response = await fetch('http://localhost:8080/blog-0.0.1-SNAPSHOT/ac/forgot-password', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Expand Down
3 changes: 2 additions & 1 deletion frontend/src/pages/LoginPage.js
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,8 @@ const LoginPage = () => {
e.preventDefault();
setAnimationKey(Date.now());
try {
const response = await fetch('http://localhost:8080/blog/ac/login', {
// const response = await fetch('http://niceblog.myvnc.com:8080/blog/ac/login', {
const response = await fetch('http://localhost:8080/blog/ac/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Expand Down
1 change: 1 addition & 0 deletions frontend/src/pages/SingleArticle.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ const SingleArticle = () => {

const fetchComments = async () => {
try {
// const response = await axios.get(`http://niceblog.myvnc.com:8080/blog/api/comments/article/${articleId}`);
const response = await axios.get(`http://localhost:8080/blog/api/comments/article/${articleId}`);
const fetchedComments = response.data;

Expand Down
3 changes: 2 additions & 1 deletion frontend/src/pages/UserData.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ const UserData = () => {
// });
if (token) {
try {
const response = await fetch('http://localhost:8080/blog/api/protected-endpoint', {
// const response = await fetch('http://niceblog.myvnc.com:8080/blog/api/protected-endpoint', {
const response = await fetch('http://localhost:8080/blog/api/protected-endpoint', {
method: 'GET',
headers: {
'Authorization': `Bearer ${token}`
Expand Down
12 changes: 10 additions & 2 deletions frontend/src/services/ArticleService.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,21 @@ const getArticleByTitle = async (title) => {
};

const createArticle = async (articleData) => {
const response = await axios.post(API_BASE_URL, articleData);
console.log(articleData);
const tagId = articleData.tag
console.log(tagId);

const response = await axios.post(API_BASE_URL, articleData, { params: { tagId }});
return response.data;
};

const updateArticle = async (articleId, articleData) => {
const response = await axios.put(`${API_BASE_URL}/${articleId}`, articleData);
console.log(articleData);
const tagId = articleData.tag;
console.log("tag is: "+tagId);
const response = await axios.put(`${API_BASE_URL}/${articleId}`, articleData, { params: { tagId }});
console.log("try fetch...");

return response.data;
};
//可加入其他請求API的方法
Expand Down
38 changes: 38 additions & 0 deletions frontend/src/services/AuthService.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { API_BASE_URL } from './apiConfig';

const getToken = () => {
return localStorage.getItem('token');
};

const getUserInfo = async () => {
const token = getToken();
if (token) {
try {
const response = await fetch(`${API_BASE_URL}/protected-endpoint`, {
method: 'GET',
headers: {
'Authorization': `Bearer ${token}`
}
});

if (response.ok) {
const data = await response.json();
return data;
} else {
throw new Error('Failed to fetch user info');
}
} catch (error) {
console.error('Error fetching user info:', error);
throw error;
}
} else {
throw new Error('No token found');
}
};

const authService = {
getToken,
getUserInfo
};

export default authService;
19 changes: 19 additions & 0 deletions frontend/src/services/TagService.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import axios from "axios";

const API_BASE_URL = 'http://localhost:8080/blog/api/tags';

const getArticleTag = async (articleId) => {
const response = await axios.get(`http://localhost:8080/blog/api/articles/${articleId}/tag`);
return response.data;
}

const getAllTags = async () => {
const response = await axios.get(`${API_BASE_URL}/all`);
return response.data;
}

const tagService ={
getArticleTag,
getAllTags
}
export default tagService;
2 changes: 2 additions & 0 deletions frontend/src/services/apiConfig.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
// src/services/apiConfig.js
export const API_BASE_URL = 'http://localhost:8080/blog/api';
23 changes: 19 additions & 4 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -36,17 +36,17 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>-->
<!-- https://mvnrepository.com/artifact/javax.mail/mail -->
<!-- https://mvnrepository.com/artifact/javax.mail/mail -->
<!--<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>-->
<!-- https://mvnrepository.com/artifact/com.sun.mail/javax.mail -->
<dependency>
<groupId>org.fusesource.jansi</groupId>
<artifactId>jansi</artifactId>
<version>2.3.3</version>
<groupId>org.fusesource.jansi</groupId>
<artifactId>jansi</artifactId>
<version>2.3.3</version>
</dependency>
<dependency>
<groupId>com.sun.mail</groupId>
Expand Down Expand Up @@ -96,6 +96,21 @@
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<!-- JUnit 5 -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.9.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.9.2</version>
<scope>test</scope>
</dependency>

<!-- Spring Boot Test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -189,4 +189,4 @@ public ResponseEntity<Map<String, String>> verifyAccount(@RequestParam("token")

return ResponseEntity.ok(Collections.singletonMap("message", message));
}
}
}
Loading

0 comments on commit 499501f

Please sign in to comment.