【发布时间】:2019-05-17 02:03:26
【问题描述】:
我有两台服务器,其中一台是用于 React 的 Webpack 服务器 (localhost:3000),另一台是用于 Express 服务器 (localhost:4000)。我读到我需要在我的package.json 文件中设置代理。好的,我做到了。但它仍然不起作用。我试图在fetch 函数上设置标题。还是不行。并且控制台中没有任何错误。
这是我的代码。
package.json
{
"name": "newsfeed",
"version": "0.1.0",
"private": true,
"proxy": "http://localhost:4000",
"dependencies": {
"npm-run-all": "^4.1.5",
"react": "^16.6.3",
"react-dom": "^16.6.3",
"react-scripts": "2.1.1"
},
"scripts": {
"start": "react-scripts start",
"dev": "run-p server start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"server": "node server_demo/server.js"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": [
">0.2%",
"not dead",
"not ie <= 11",
"not op_mini all"
]
}
src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './style.css';
class NewsBlock extends React.Component {
constructor() {
super();
this.state = {
data: ''
}
}
componentDidMount() {
fetch('localhost:4000/',{
credentials: 'include',
headers: {
'Content-Type': 'application/json'
}
}).then(res => res.json()).then(data => this.setState({data}));
}
render() {
return <div>
{this.state.data}
</div>
}
}
ReactDOM.render(
<NewsBlock/>,
document.getElementById('root')
)
server_demo/server.js
const exp = require('express');
const app = exp();
app.listen(4000, () => console.log('Listening on 4000'));
app.use(exp.static('./'));
app.get('/', (req, res) => {
res.setHeader('Content-Type', 'application/json');
res.json({
"glossary": {
"title": "example glossary"
}
});
})
【问题讨论】:
标签: reactjs express proxy localhost package.json