我正在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上运行我的应用程序,但不确定为什么会发生任何提示,建议将不胜感激。
答案 0 :(得分:1)
您的错误是自解释的,404表示http://localhost:8080/cards不可用,因此与此处无关,请首先检查您的应用程序服务器响应。 您可以使用 postman 或任何其他工具来验证其余响应,然后再继续执行React。
这里有一个自定义的示例https://w7xr8.codesandbox.io