首页 > 解决方案 > 无法从一个本地主机服务器获取资源到另一个

问题描述

我有两台服务器,其中一台是用于 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"
        }
    });

})

标签: reactjsexpressproxylocalhostpackage.json

解决方案


您不需要package.json. 将CORS 中间件添加到您的 Express 服务器。

app.use(cors({
  origin: true,
  credentials: true,
}))

推荐阅读