使用React的代理设置从Featherjs后端获取数据

问题描述 投票:0回答:1

我可能完全误解了这一点,但我正在尝试获得一个Featherjs后端服务,在本地运行(localhost:3030 / forms),可以从create-react-app客户端(localhost:3000)访问。

我在客户端上设置了package.json文件,包括:

{
  ...
  "proxy": "http://localhost:3030",
  ...
}

...而App.js现在看起来像这样:

import React, { Component } from "react";
import "./App.css";

class App extends Component {
  state = { forms: [] };

  componentDidMount() {
    fetch("/forms")
      .then(res => res.json())
      .then(forms => this.setState({ forms }));
  }

  render() {
    return (
      <div className="App">
        <h1>Forms</h1>
        {this.state.forms.data.map(myForm => (
          <div key={myForm._id}>{myForm.package_id}</div>
        ))}
      </div>
    );
  }
}

export default App;

当我在浏览器中点击localhost:3030/forms网址时,我得到了我期待的JSON:

{
  total: 1,
  limit: 10,
  skip: 0,
  data: [
    {
      columns: "8",
      datarows: [
        {
          age: 49,
          childcount: 1,
          firstname: "Darius",
          gender: "m",
          group: 1,
          insideLegMeasurement: 144,
          lastname: "Holder"
        }
      ],
      package_id: "1234",
      rows: "2",
      _id: "k6M3zRoDfZ0EKWBw"
    }
  ]
}

我似乎没有收到CORS错误,但代理请求似乎没有被传递。相反,我得到一个“TypeError:无法读取属性'地图'未定义”错误... :-(

确切地说,从1到11的等级,我是多么愚蠢?或者,我应该做些什么才能让它发挥作用?

javascript reactjs proxy cors feathersjs
1个回答
2
投票

proxy出现在您的请求路径中时,将使用/api字段中的URL。所以/forms将不起作用,但例如/api/forms将代表http://localhost:3030/api/forms

如果您使用[email protected]或更高版本,您可以添加src/setupProxy.js文件并根据自己的喜好自定义代理http-proxy-middleware

这就是你如何做到这一点所以你的/forms请求被发送到http://localhost:3030

// src/setupProxy.js
const proxy = require('http-proxy-middleware');

module.exports = function(app) {
  app.use(proxy('/forms', { target: 'http://localhost:3030/' }));
};
© www.soinside.com 2019 - 2024. All rights reserved.