Javascript 如何从nodejs服务器获取json?
下面是带有react的前端和带有nodejs/expresjs的后端。我可以正确地将数据下载到后端,但当我尝试将数据下载到前端时,它总是给我一个 SyntaxError:JSON.parse:JSON数据第1行第1列的数据意外结束[Learn More]” 但是我以前使用过类似的格式,没有问题。有人能给我一些建议吗 谢谢大家! 前端Javascript 如何从nodejs服务器获取json?,javascript,node.js,reactjs,google-cloud-datastore,Javascript,Node.js,Reactjs,Google Cloud Datastore,下面是带有react的前端和带有nodejs/expresjs的后端。我可以正确地将数据下载到后端,但当我尝试将数据下载到前端时,它总是给我一个 SyntaxError:JSON.parse:JSON数据第1行第1列的数据意外结束[Learn More]” 但是我以前使用过类似的格式,没有问题。有人能给我一些建议吗 谢谢大家! 前端 import React from 'react'; export default () => { let images = fetch('http:/
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>
}
我担心您的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>
}
}
类组件扩展React.Component{
组件安装(){
取('http://localhost:3000/datastore', {
模式:“无cors”,//无cors,cors,*相同来源
缓存:“无缓存”,//*默认值,无缓存,重新加载,强制缓存,仅在缓存时
凭证:“同一来源”、//包括、同一来源、*省略
})
.then(response=>response.json())
.then(images=>this.setState({images});
}
渲染(){
const{images}=this.state//使用此
返回。。。
}
}
同样,这一切都假设端点返回有效的JSON。完整回答。但让我解释一下。无论何时使用fetch调用api,它都返回Promise它基本上是异步的,就像“调用api并等待它响应”。所以
这行图像是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行之前执行。我建议您阅读《承诺》,
之前的异步代码。
这里有更好的方法
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;
端点JSON看起来像什么?它看起来像是任务从一个
对象的数组到一个字符串的随机过程?我以前把它作为一个对象使用过,但它仍然给了我同样的错误导航到/curlhttp://localhost:3000/datastore
并将回答粘贴到您的问题中。?!您可以查看“网络”选项卡并看到了吗?这只是更好地组织了我的文件,但并没有回答我的主要问题:(我在问如何将数组从后端发送到前端请参考我的评论。因此,我以这种方式更改了我的文件,但它仍然没有将数组发送到前端。是的,因为后端返回无效的JSON。那么为什么我卷曲它时它返回JSON?
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;