你如何从 nodejs 服务器获取 json?
How do you fetch a json from nodejs server?
下面是前端用react,后端用nodejs/expresjs。我可以正确地将数据获取到后端,但是当我尝试将数据下载到我的前端时,它不断给我一个
SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data[Learn More]"
但我之前使用过类似的格式,没有遇到任何问题。谁能给我一些关于这个问题的建议?
谢谢!
前端
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;
我对您的 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>
}
}
同样,这一切都假定端点 returns 有效 JSON。
Tyler Sebastian 完整回答。但是让我解释一下。每当你使用 fetch 调用 api 它 return Promise 它基本上是异步的所以它像 "calling api and waiting for it response"。所以
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对象。
当你调用 .then 时。当它完成从后端获取数据时,它会响应你。
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);
}
错误实际上是在后端。我不允许交叉来源
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;
下面是前端用react,后端用nodejs/expresjs。我可以正确地将数据获取到后端,但是当我尝试将数据下载到我的前端时,它不断给我一个
SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data[Learn More]"
但我之前使用过类似的格式,没有遇到任何问题。谁能给我一些关于这个问题的建议?
谢谢!
前端
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;
我对您的 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>
}
}
同样,这一切都假定端点 returns 有效 JSON。
Tyler Sebastian 完整回答。但是让我解释一下。每当你使用 fetch 调用 api 它 return Promise 它基本上是异步的所以它像 "calling api and waiting for it response"。所以
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对象。 当你调用 .then 时。当它完成从后端获取数据时,它会响应你。
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);
}
错误实际上是在后端。我不允许交叉来源
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;