【问题标题】:ReactJS and Express with Axios returning 404ReactJS 和 Express 与 Axios 返回 404
【发布时间】:2019-04-17 01:43:39
【问题描述】:

不确定我的代码发生了什么,但我正在尝试使用 axios 控制台记录一些内容进行测试运行,但我得到了 404。

class SubscribeForm extends Component {
  constructor(props) {
    super(props);
    this.state = {value: ''};

    this.emailChange = this.emailChange.bind(this);
    this.emailSubmit = this.emailSubmit.bind(this);
  }

  emailChange(e) {
    this.setState({value: e.target.value});
  }

  emailSubmit(e) {
    e.preventDefault();
    axios.post('/subscribe', {
      email: 'someemail@email.com',
      headers: {
        'Content-Type': 'application/json;charset=UTF-8',
        "Access-Control-Allow-Origin": "*",
      }
    }).then(res => {
      if(res.data.success) {
        this.setState({email: ''})
      }
    }).catch(error => {
      if (error.response) {
        // The request was made and the server responded with a status code
        // that falls out of the range of 2xx
        console.log(error.response.data);
        console.log(error.response.status);
        console.log(error.response.headers);
      } else if (error.request) {
        // The request was made but no response was received
        // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
        // http.ClientRequest in node.js
        console.log(error.request);
      } else {
        // Something happened in setting up the request that triggered an Error
        console.log('Error', error.message);
      }
      console.log(error.config);
    });
  }

  render() {
    const { classes } = this.props;
    return (
      <div className={classes.subFormSection}>
        <p className={classes.formHelper}>
          Join the club, enter your email address
        </p>

        <form method="post" className={classes.subFormWrap} onSubmit={this.emailSubmit}>
          <TextField
            value = {this.state.value}
            onChange = {this.emailChange}
          />
          <Button
            className={classes.button}
            type="submit"
          >
            Send
            <Icon className={classes.rightIcon}>send</Icon>
          </Button>
        </form>
      </div>
    );
  }
}

我尝试在 axios 中添加标头以查看是否是问题所在,但我认为不是(或者我做错了)。

另外,我没有 /subscribe 文件,我想我不需要吗?因为,我在这里用 express 捕捉它:

const cors = require("cors");

app.use(cors());

app.post("/subscribe", (req, res, next) => {
  console.log(req.body.email);
});

此文件在我的服务器文件中,而反应部分在客户端文件中。我设置了代理,所以当我运行服务器时,前端和后端正在相互通信。


已更新 404 状态已转(待处理)

我还在客户端文件夹setupProxy.js中设置了代理中间件

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

module.exports = function(app) {
  app.use(proxy("/subscribe", {
    target: "http://localhost:5000"
  }));
};

我正在获取/subscrib 的网络请求中的请求标头:

Provisional headers are shown

这会导致它(待定)吗?

【问题讨论】:

    标签: reactjs forms react-native react-redux axios


    【解决方案1】:

    据我所知,您的服务器和客户端应用程序似乎运行在不同的端口上。如果是这种情况,您不能这样做:

    axios.post('/subscribe', {
          email: 'someemail@email.com',
          headers: {
            'Content-Type': 'application/json;charset=UTF-8',
            "Access-Control-Allow-Origin": "*",
          }
    })
    

    您正在使用没有主机的路径/subscribe。 Axios 尝试使用运行您的客户端应用程序的主机,但它找不到该路径,因此找不到 404 状态代码。

    如果是这种情况,您可以通过在 /subscribe 路径之前使用服务器的主机和端口来修复它。见下文:

    axios.post('localhost:4000/subscribe', {
          email: 'someemail@email.com',
          headers: {
            'Content-Type': 'application/json;charset=UTF-8',
            "Access-Control-Allow-Origin": "*",
          }
    })
    

    请将此处的端口localhost:4000 更改为您的服务器端口。

    注意:这仅适用于您的本地开发。

    如果您计划部署应用程序,您可能希望改用 process.env.PORT

    【讨论】:

    • 谢谢,我设置了一个 http-proxy-middleware,并将路由连接到我服务器的 localhost 端口。
    • 嘿,我现在的状态是“待定”。我知道这不是问题的一部分,但你知道为什么它没有给我一个正确的状态吗?
    • 嗨,我用代理代码更新了我的问题。这帮助我连接了服务器和客户端,但现在我的 /subscribe 处于待处理状态。我在网络请求中也有Provisional headers are shown。这可能是个问题吗?
    • 在它挂起的情况下,您似乎没有将响应发送回客户端。您的 /subscribe 路线中只有 console.log(req.body.email)。使用res.send(...) 发回响应。
    • 哦!惊人的!谢谢!!是的,我现在的状态是200。谢谢!
    【解决方案2】:

    您可以使用浏览器的检查元素来检查请求是否正确(检查元素>网络)。

    通过查看代码,我认为您缺少基本网址。

    应该是这样的

    axios.post(baseul + port + request url)
    

    示例:

    axios.post('http://localhost:3000/subscribe')
    

    【讨论】:

    • 不幸的是,事实并非如此。我的错误是:POST http://localhost:3000/subscribe 404 (Not Found)
    • @hellomello 错误说 localhost:3000 这意味着它正在尝试连接端口 3000。如果您尝试在不同的端口上连接 express,请确保它也在调用正确的端口.
    • @Fawaz 这个评论让我意识到我必须专门为/subscribe 设置代理。我已经在其他路线上这样做了,但忘记了我需要用这条路线进行设置!谢谢!
    • @hellomello 很高兴它有帮助!
    猜你喜欢
    • 1970-01-01
    • 2018-12-23
    • 2021-11-05
    • 2019-03-17
    • 1970-01-01
    • 2020-12-18
    • 2021-06-01
    • 2018-10-08
    • 2021-03-14
    相关资源
    最近更新 更多