从'/'获取数据

时间:2019-02-24 10:03:45

标签: node.js reactjs fetch

我一直在关注有关react和node的教程,并且在每个教程中他们都使用类似

app.get('/api/blahblah', (req, res)=>{
  res.send('something')
})

然后他们从api / blahblah获取“内容”,并在默认路由('/')中获取该“内容”  所以我试图发送一些东西到“ /”并从“ /”中获取数据,但是没有用 并给了我这个错误

  

未处理的拒绝(SyntaxError):JSON中位置0的意外令牌<< / p>

我当前正在使用此代码:

反应

// Fetch the list on first mount
componentDidMount() {
 this.getList();
}

// Retrieves the list of items from the Express app
getList = () => {
fetch('/main')
.then(res => res.json())
.then(list => this.setState({ list }))
}

NodeJS

app.get('/main', (req,res) => {
var list = ["itdemfs1", "item2", "item3"];
res.json(list);
console.log('Sent list of items');
});

和无效的代码

 ***REACT***:

// Fetch the list on first mount
componentDidMount() {
 this.getList();
}

// Retrieves the list of items from the Express app
getList = () => {
fetch('/')
.then(res => res.json())
.then(list => this.setState({ list }))
}

NodeJS

app.get('/', (req,res) => {
var list = ["itdemfs1", "item2", "item3"];
res.json(list);
console.log('Sent list of items');
});

1 个答案:

答案 0 :(得分:0)

由于在React中,您是从“ /” 获取的,如果将NodeJS更改为

会怎样?
app.get('/', (req,res) => {
  var list = ["itdemfs1", "item2", "item3"];
  res.json(list);
  console.log('Sent list of items');
});

我相信它应该可以解决问题

相关问题