【发布时间】:2019-07-06 21:37:42
【问题描述】:
我正在 ReactJs 中构建 CRUD 应用程序并尝试从 json 文件中添加、删除和获取数据。
当我尝试从 db.json 文件中获取数据时出现以下错误
GET http://localhost:8080/cards 404 (Not Found)
"Unexpected token < in JSON at position 0"
db.json
{
"cards": [
{
"id": 0,
"image": "http://placehold.it/400x300",
"category": "CATEGORY 0",
"placeholder": "Placeholder 0"
},
{
"id": 6,
"image": "http://placehold.it/400x300",
"category": "CATEGORY AAAA",
"placeholder": "Placeholder BBB"
},
{
"id": 7,
"image": "http://placehold.it/400x300",
"category": "CATEGORY AAAA",
"placeholder": "Placeholder BBB"
}
]
}
cardSaga.js
import { call, put, takeLatest } from 'redux-saga/effects'
//
// fetch all cards
//
export function fetchCardsFromServer() {
return fetch('http://localhost:8080/cards')
.then(response => response.json());
}
function* fetchCards() {
try {
const cards = yield call(fetchCardsFromServer);
yield put({type: "FETCH_CARDS_SUCCEEDED", cards: cards});
} catch (e) {
yield put({type: "FETCH_CARDS_FAILED", message: e.message});
}
}
//
// add card
//
export function postCardToServer() {
const card = {
"image": "http://placehold.it/400x300",
"category": "CATEGORY AAAA",
"placeholder": "Placeholder BBB"
}
return fetch("http://localhost:8080/cards",{
method: "POST",
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: JSON.stringify(card)
})
.then(response => response.json());
}
function* addCard() {
try {
const card = yield call(postCardToServer);
yield put({type: "ADD_CARD_SUCCEEDED", card: card});
} catch (e) {
yield put({type: "ADD_CARD_FAILED", message: e.message});
}
}
//
// remove card
//
export function removeCardAtServer(id) {
return fetch("http://localhost:8080/cards" + id,{
method: "DELETE"
})
.then(response => response.json());
}
function* removeCard(action) {
try {
yield call(removeCardAtServer, action.id);
yield put({type: "REMOVE_CARD_SUCCEEDED", index: action.id});
} catch (e) {
yield put({type: "REMOVE_CARD_FAILED", message: e.message});
}
}
function* cardSaga() {
//fetch all
yield takeLatest("FETCH_CARDS", fetchCards);
//add
yield takeLatest("ADD_CARD", addCard);
//add
yield takeLatest("REMOVE_CARD", removeCard);
}
export default cardSaga;
当我尝试将卡片添加到 db.json 文件时,出现以下错误
POST http://localhost:8080/cards 404 (Not Found)
"Unexpected token < in JSON at position 0"
当我打开我的网络选项卡并在控制台中响应时,我看到的只是这个
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot GET /cards</pre>
</body>
</html>
我在 localhost:8080 上运行我的应用程序,但我不确定为什么会发生这种情况,任何提示和建议将不胜感激。
【问题讨论】:
-
很可能您收到的是 html 响应,请尝试打开网络选项卡并检查原始响应
-
是的,我只看到 html 代码并且无法获取 /cards