[英]How do you fetch a json from nodejs server?
Below is the front end with react and the backend with nodejs/expresjs.下面是带有 react 的前端和带有 nodejs/expresjs 的后端。 I can correctly get the data to the backend but when I try to download the data to my front end it constantly gives me a我可以正确地将数据发送到后端,但是当我尝试将数据下载到我的前端时,它不断给我一个
SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data[Learn More]" SyntaxError: JSON.parse: JSON 数据第 1 行第 1 列的数据意外结束[了解更多]"
But I have used a similar format prior and had no issues.但是我之前使用过类似的格式并且没有问题。 Can anyone give me any advice on the issue?任何人都可以就这个问题给我任何建议吗?
Thank you!谢谢!
frontend前端
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>
}
backend后端
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;
The error was actually in the back-end.错误实际上是在后端。 I didn't allow cross origin我不允许交叉起源
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;
Tyler Sebastian answer in full.泰勒塞巴斯蒂安完整回答。 But let me explain it.但让我解释一下。 Whenever u call api using fetch It return Promise it is basically async so it like "calling api and waiting for it response".每当你使用fetch调用 api 它返回Promise它基本上是异步的,所以它就像“调用 api 并等待它响应”。 So所以
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
});
This line images is Promise Object.这一行图像是Promise对象。 When u call .then on it.当你调用.then时。 It will response you when it finished fetching data from backend.当它完成从后端获取数据时,它会回应你。
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
Line number 6 maybe execute before line number 5. I suggest you to read Promise , asynchronous code before.第 6 行可能会在第 5 行之前执行。建议您先阅读Promise异步代码。 Here is better way to do that.这是更好的方法。
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);
}
I have concerns about your API endpoint... See my comments.我对您的 API 端点感到担忧...请参阅我的评论。
Regarding the component:关于组件:
fetch
is asynchronous - images
is a Promise
, not the actually response from the endpoint. fetch
是异步的 - images
是一个Promise
,而不是来自端点的实际响应。 You need to use component state您需要使用组件状态
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>
}
}
again this all assumes that the endpoint returns valid JSON.同样,这一切都假设端点返回有效的 JSON。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.