我正在尝试更改数据库中的某些数据,但是一旦调用api请求,我就会收到错误消息:
Uncaught (in promise) SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
伴随着相应的网络错误404
。我不太确定为什么它不能识别我的api调用,这是最初的访存调用:
import fetch from '../../../../core/fetch/fetch.server';
import history from '../../../../core/history';
export default function checkIn(orderId) {
debugger;
return async (dispatch, getState) => {
// dispatch({ type: BOXOFFICE_CHECKING_IN });
const response = await fetch(`/api/orders/${orderId}/checkIn`, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
checkedIn: true,
}),
}
);
if (response.status === 200) {
// dispatch({ type: BOOKING_CHECKED_IN });
} else {
const errorResponse = await response.json();
if (errorResponse.code === 'card_error') {
// dispatch({ type: BOXOFFICE_CHECKED_IN_ERROR });
}
}
} catch (err) {
throw err;
}
};
}
还有我的api文件(删除了所有不相关的内容):
import { Router } from 'express';
import checkIn from '../handlers/api/orders/checkInCustomer';
export default (resources) => {
const router = new Router();
router.post('/orders/:orderId/checkIn', checkIn(resources));
return router;
};
这最终是要调用我的js文件来更改数据数据库条目:
import { defaultTo } from 'lodash';
import guuid from '../../../../../../core/guuid';
import authenticateAdmin from '../authenticateAdmin';
import order from '../../../../client/reducers/ui/modals/order';
export default ({ knex }) =>
authenticateAdmin(knex)(async (req, res) => {
try {
console.log('checkinCustomer');
const { orderId } = req.params;
const { isCheckedIn } = req.body;
console.log(orderId);
console.log(isCheckedIn);
await knex('orders').where('is_checked_in', '=', orderId).update({ is_checked_in: isCheckedIn }).where({ id: orderId });
res.status(201).end();
} catch (err) {
console.error(err.stack || err);
}
});
任何人都可以发现我的代码中根本上有错误的地方吗,我可以向您保证文件路径都是正确的,并且所有函数彼此可见,也许这就是我解析数据的方式了?
EDIT
我认为包括我也收到CORS错误可能是有用的:
Access to XMLHttpRequest at 'http://localhost:3000/api/orders/c7216fc0-1197-4cb6-99d4-15760f00b6e7/checkIn' from origin 'my site name' has been blocked by CORS policy:
进一步编辑
我已设法删除了原始的JSON错误,但是仍然遇到404
网络错误以及原始的CORS错误...此外,如果我更改提取的最后一部分从checkIn
说到cancel
(这是一个完全正常的api调用),同样的错误仍然存在。
答案 0 :(得分:1)
在向身体传递数据时,请勿使用application/json
。
使用{{1}}时,您应该在体内传递 json 格式。
答案 1 :(得分:0)
我有解决办法!原来我的import fetch from '../../../../core/fetch/fetch.server';
在初始文件中是错误的,应该从'../../../../core/fetch/fetch';
导入获取!