Axios的ReactJS和Express返回404 [英] ReactJS and Express with Axios returning 404

查看:141
本文介绍了Axios的ReactJS和Express返回404的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不确定我的代码是怎么回事,但是我试图通过axios控制台进行测试运行以注销某些内容,但是我得到了404.

Not sure what's going on with my code, but I'm trying to just do a test run with axios console logging something out, but I'm getting a 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中以查看是否是问题所在,但我不认为这是问题所在(或者我做错了).

I tried adding headers into axios to see if thats the issue, but i don't think it is (or perhaps I'm doing it wrong).

此外,我没有/subscribe文件,我认为我不需要一个文件吗?因为,我在这里用express捕获它:

Also, I don't have a /subscribe file, I don't think I need one? Since, I'm capturing it with express here:

const cors = require("cors");

app.use(cors());

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

此文件位于我的服务器文件中,而react部分位于客户端文件中.我已经设置了代理,因此当我运行服务器时,前端和后端正在互相通信.

This file is within my server files, while the react portion is within client files. I have proxy set up, so when I have run the server, front end and back end is talking to each other.

已更新的404状态变为(待处理)

我还在客户端文件夹 setupProxy.js

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

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

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

I'm getting in the request header in my network request for /subscrib:

Provisional headers are shown

这是否导致它处于(待处理)状态?

Is this causing it to be (pending)?

推荐答案

据我所知,您的服务器和客户端应用程序似乎在不同的端口上运行.如果是这种情况,您将无法执行以下操作:

From what I can see, it seem your server and client app run on different ports. If that is the case you cannot do this:

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

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

You are using the path /subscribe without a host. Axios tries to use the host from which your client app is running and it doesn't find that path hence the 404 status code.

在这种情况下,您可以通过使用服务器的主机和端口(位于/subscribe 路径之前)来进行修复.见下文:

If this is the case, you can fix it by using the host and port of your server before the /subscribe path. See below:

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

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

Kindly change the port here localhost:4000 to your server port.

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

Note: This is for your local development only.

如果您打算部署应用程序,则可能要改用 process.env.PORT .

If you plan on deploying the app, you might want to use process.env.PORT instead.

这篇关于Axios的ReactJS和Express返回404的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆