reactjs - 无法从一个本地主机服务器获取资源到另一个
问题描述
我有两台服务器,其中一台是用于 React () 的 Webpack 服务器localhost:3000
,另一台是用于 Express 服务器 ( localhost:4000
)。package.json
我读到我需要在我的文件中设置代理。好的,我做到了。但它仍然不起作用。我试图在fetch
函数上设置标题。还是不行。并且控制台中没有任何错误。
这是我的代码。
包.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"
}
});
})
解决方案
您不需要package.json
. 将CORS 中间件添加到您的 Express 服务器。
app.use(cors({
origin: true,
credentials: true,
}))
推荐阅读
- sql - Activeadmin 自定义过滤器失败
- security - 如何在使用 SAML2 的 IDP 发起的 SSO 中防止重放攻击
- python-2.7 - Python selenium 使用便携式 Firefox 创建 webdriver
- angular - 想用管道返回新的可观察对象,每次都传入新数据。使用 Angular 6
- java - 如果基类匹配条件,IntelliJ 结构搜索会查找派生类
- sql - 什么查询以大写形式显示我的表上的所有数据?
- java - 在 java rest api 中创建实例与使用注解注入
- cordova - 尝试访问 Meteor 应用程序中的本地文件,但无法触发 document.addEventListener("deviceready", onDeviceReady, false);
- powershell - 尝试创建一个powershell用户创建脚本,如果它已经存在,想要将数字附加到用户名
- c - Bash,如何检查 C 程序是否超时