首页 > 解决方案 > React fetch 到 Express API 不起作用,有什么提示吗?

问题描述

我正在尝试对我的 express api 进行简单的 fetch 调用,但我无法让它工作,响应为 200,但我得到的是 index.html 而不是我想要的 JSON。这是我的场景:

包.json

"version": "1.0.0",
  "description": "Application to show FrontEnd knowledge",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "webpack-dev-server --config webpack.config.js",
    "build": "webpack --config webpack.config.js --mode production"
  },
  "proxy": "http://localhost:5000/",

反应组件代码

  callBackendAPI = () => {
    const body = fetch("/api/hello")
    .then(res => res.text())          // convert to plain text
    .then(text => console.log(text))  // then log it out

    return body;re
  };

表达 server.js 代码

const express = require('express');
const bodyParser = require('body-parser');

const app = express();
const port = process.env.PORT || 5000;

app.use(bodyParser.json());


app.get('/', function(req, res) {
    res.sendFile(__dirname + '/public/index.html');
})

// create a GET route
app.get('/api/hello', (req, res) => {
    res.send({ express: 'Hello From Express' });
  });



  // console.log that your server is up and running
app.listen(port, () => console.log(`Listening on port ${port}`));

标签: reactjsapiexpress

解决方案


从您的服务器代码看来,您正在发送回 JSON,但在您的前端代码中,您正在寻找文本。

 callBackendAPI = () => {
    const body = fetch("/api/hello")
    .then(res => res.json())         
    .then(data => console.log(data.express))
  };

推荐阅读