下面是带有react的前端,以及带有nodejs / expresjs的后端。我可以正确地将数据发送到后端,但是当我尝试将数据下载到前端时,它不断为我提供
SyntaxError:JSON.parse:JSON数据第1行第1列的数据意外结束[了解更多]“
但是我以前使用过类似的格式,没有问题。有人可以给我关于这个问题的任何建议吗?
谢谢!
前端
import React from 'react';
export default () => {
let images = fetch('http://localhost:3000/datastore', {
mode: "no-cors", // no-cors, cors, *same-origin
cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
credentials: "same-origin", // include, same-origin, *omit
})
.then(response => response.json());
console.log(images);
images.forEach((u, i) => {
console.log(images[i])
});
return <div>
</div>
}
后端
var express = require('express');
var router = express.Router();
let Datastore = require('@google-cloud/datastore')
const datastore = Datastore();
const query = datastore.createQuery('image');
router.get('/', function(req, res, next){
datastore
.runQuery(query)
.then(results => {
let tasks = results[0];
console.log('Tasks:');
tasks.forEach(task => {
const taskKey = task[datastore.KEY];
console.log(taskKey.id, task);
});
console.log(tasks);
return res.send(tasks);
})
.catch(err => {
console.error('ERROR:', err);
return res.status(200).send({
success: false
});
});
});
module.exports = router;
答案 0 :(得分:1)
该错误实际上是在后端。我不允许跨原点
var express = require('express');
var router = express.Router();
let Datastore = require('@google-cloud/datastore')
const datastore = Datastore();
const query = datastore.createQuery('image');
router.get('/', function(req, res, next){
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
datastore
.runQuery(query)
.then(results => {
let tasks = results[0];
console.log('Tasks:');
tasks.forEach(task => {
const taskKey = task[datastore.KEY];
console.log(taskKey.id, task);
});
console.log(tasks);
return res.send(tasks);
})
.catch(err => {
console.error('ERROR:', err);
return res.status(200).send({
success: false
});
});
});
module.exports = router;
答案 1 :(得分:0)
Tyler Sebastian完整答案。但是,让我解释一下。每当您使用 fetch 调用api时,它都会返回 Promise ,它基本上是异步的,因此就像“调用api并等待其响应”一样。所以
let images = fetch('http://localhost:3000/datastore', {
mode: "no-cors", // no-cors, cors, *same-origin
cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
credentials: "same-origin", // include, same-origin, *omit
});
此行图像是 Promise 对象。 当您致电。然后。从后端获取数据完成后,它会响应您。
let images = fetch('http://localhost:3000/datastore', {
mode: "no-cors", // no-cors, cors, *same-origin
cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
credentials: "same-origin", // include, same-origin, *omit
}).then(response => response.json()); //1 This line of code
console.log(images); // 2 and this line of code
第6行可能在第5行之前执行。我建议您阅读 Promise , 异步代码之前。 这是更好的方法。
fetch('http://localhost:3000/datastore', {
mode: "no-cors", // no-cors, cors, *same-origin
cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
credentials: "same-origin", // include, same-origin, *omit
}).then(response => {
printImages(response); //Note that this is not your data, images array will be deep down in response.response.data
});
printResponse = (response) => {
console.log(response);
}
答案 2 :(得分:-1)
我担心您的API端点...请参阅我的评论。
关于组件:
fetch
是异步的-images
是 Promise
,而不是来自端点的实际响应。您需要使用组件状态
class Component extends React.Component {
componentDidMount () {
fetch('http://localhost:3000/datastore', {
mode: "no-cors", // no-cors, cors, *same-origin
cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
credentials: "same-origin", // include, same-origin, *omit
})
.then(response => response.json())
.then(images => this.setState({ images });
}
render () {
const { images } = this.state // use this
return <div> ... </div>
}
}
同样,所有这些操作都假设端点返回了有效的JSON。