如何使代理指向端口3001

时间:2019-04-18 22:26:32

标签: javascript node.js reactjs

我有一个用node / express创建的服务器,该服务器从url返回这些数据:http://localhost:3001/api/users

[{"id":1,"username":"frank"},{"id":2,"username":"lowi"}]

这是服务器代码:

const express = require('express');
const app = express();
const proxy = require('http-proxy-middleware');

app.use(proxy('/api', { target: 'http://localhost:3001/' }));

app.get('/api/users', (req, res) => {
  res.json([
    {
      id: 1,
      username: 'frank'
    },
    {
      id: 2,
      username: 'lowi'
    }
  ])
});

app.get('/api/cars', (req, res) => {
  res.json([
    {
      id: 1,
      brand: 'bmw'
    },
    {
      id: 2,
      brand: 'nissan'
    }
  ])
});

const port = process.env.port || 3001;
app.listen(port);

但是当我尝试使用axios从客户端访问这些数据时,我会出错

  

获取http://localhost:3000/api/users 404(未找到)

这是客户端代码:

import React, { Component } from 'react';
import axios from 'axios';
import logo from './logo.svg';
import './App.css';

class App extends Component {

  componentWillMount() {
    axios.get('/api/users')
    .then(res => {
      console.log(res.data);
    });
  }

  render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <p>
            Edit <code>src/App.js</code> and save to reload.
          </p>
          <a
            className="App-link"
            href="https://reactjs.org"
            target="_blank"
            rel="noopener noreferrer"
          >
            Learn React
          </a>
        </header>
      </div>
    );
  }
}

export default App;

1 个答案:

答案 0 :(得分:1)

找到了解决方案。根据文档here

我必须在客户端应用程序setupProxy.js文件夹下的/src文件中设置代理!!!

const proxy = require('http-proxy-middleware');

module.exports = function(app) {
    app.use(proxy('/api', { target: 'http://localhost:3001' }));
};

哭泣...