我正在尝试对我的express api进行简单的访存调用,但我无法使其正常工作,响应为200,但我得到的是index.html而不是所需的JSON。这是我的情况:
package.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}`));
答案 0 :(得分:0)
从服务器代码中看,您似乎正在发送回JSON,但是在前端代码中,您正在寻找文本。
callBackendAPI = () => {
const body = fetch("/api/hello")
.then(res => res.json())
.then(data => console.log(data.express))
};