【发布时间】:2020-11-29 23:00:52
【问题描述】:
拜托,我有一个 nodejs 产品 API,它显示待售产品列表和价格。它与邮递员配合得很好。现在,我想将它连接到我的反应前端。我的 nodejs 服务器在端口 http://localhost:8001 上运行,而我的 react 服务器在端口 http://localhost:3000 上运行。在我的 react 的 package.json 文件中,我在脚本对象下方添加了“proxy”:“http://localhost:8001/”。 但是当我从我的反应前端进行提取时,我收到错误“SyntaxError:JSON.parse:JSON 数据的第 1 行第 1 列的意外字符”。我试图将我的结果记录到控制台,但没有任何显示。 以下是我的代码。
React 中的 App.js 文件
import React, { Component } from 'react';
import './App.css';
class App extends Component {
constructor(props) {
super(props);
this.state = {
response: ""
}
}
callAPI() {
fetch('/products')
.then(res => res.json())
.then((result) => {
this.setState({ response: result })
},
(error) => console.log(error)
);
}
componentDidMount() {
this.callAPI();
}
render() {
return(
<>
<h1>{this.state.response}</h1>
</>
)
}
}
我在 react 中的 package.json 文件
{
"name": "my-app",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.11.6",
"@testing-library/react": "^11.2.2",
"@testing-library/user-event": "^12.2.2",
"axios": "^0.21.0",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-scripts": "4.0.1",
"web-vitals": "^0.2.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"proxy": "http://localhost:8001/",
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
我在 node.js 中的 app.js 文件
require('dotenv').config();
const express = require('express');
const morgan = require('morgan');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const cors = require('cors');
const path = require('path');
const app = express();
app.use(cors());
app.use(morgan('dev'));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// For people to access your API from other hosts
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header(
'Access-Control-Allow-Origin',
'Origin, X-Requested-With, Content-Type, Accept, Authorization'
);
if (req.method === 'OPTIONS') {
res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE');
return res.status(200).json({});
}
next();
})
app.get('/products', (req, res, next) => {
res.send({ "express": "Hello from express" });
});
app.use((req, res, next) => {
const error = new Error('Not found');
error.status = 404;
next(error);
})
app.use((error, req, res, next) => {
res.status(error.status || 500);
res.json({
error: {
message: error.message
}
})
})
module.exports = app;
【问题讨论】:
标签: javascript node.js json reactjs express