简体   繁体   English

与ExpressJ一起使用Create-React-App

[英]Using Create-React-App with ExpressJs

Ok so I have a very simple app with create-react-app . 好的,所以我有一个非常简单的具有create-react-app的应用程序 Now I'm using ExpressJS to handle API calls that I am making with the $.ajax() method inside of my react app within the componentWillMount() method. 现在,我正在使用ExpressJS来处理我在componentWillMount()方法内的我的应用程序中使用$ .ajax()方法进行的API调用。

So all the React front end has is a simple form with 1 input field and submit like so: 所以所有React前端都有一个带有1个输入字段的简单表单,并像这样提交:

import React, { Component } from 'react';
import $ from 'jquery';
import './App.css';

class App extends Component {


  componentDidMount(){

      $('form').on('submit', function(e) {
        e.preventDefault();

        $.ajax({
          url: '/api',
          type: 'post',
          data: $('form').serialize(),
          dataType: 'json',
          success: function(data) {
            console.log('successful ajax request made!');
          }
        });

      });
  }

  render() {
    return (
      <div className="App">
        <form method="POST">
          <input type="text" name="title" />
          <input id="submit" type="submit" />
        </form>
      </div>
      );
  }
}

export default App;

Now my express route look like this: 现在,我的快速路线如下所示:

var express = require("express");
var router = express.Router();

router.post("/api", function(req, res, next){
    console.log(req.body);
});

module.exports = router;

THE PROBLEM 问题

When running create-react-app with npm start it goes to localhost:3000 do to the Webpack local dev server and when I fire off my app.js in my server directory with node server/app.js is goes to localhost:3001 because they cannot run in the same port. 当运行创建反应的应用程式NPM开始它去到localhost:3000做对的WebPack本地开发服务器,当我与节点服务器我的服务器目录火了我的app.js / app.js是去为localhost:3001,因为它们不能在同一端口中运行。

Because of this I cannot make proper API calls without getting an error showing that the POST request has failed. 因此,我无法进行正确的API调用,而不会收到显示POST请求失败的错误消息。

So now the golden question is how can I make API calls from a local server on 2 different ports? 因此,现在的黄金问题是如何从两个不同端口上的本地服务器进行API调用?

If you need any more info about my code i'd be more than happy to post it. 如果您需要有关我的代码的更多信息,我很乐意将其发布。 Help is greatly appreciated, thank you! 非常感谢您的帮助,谢谢!

Add this line in your existing client Package.json file 在您现有的客户端Package.json文件中添加此行

"proxy": {
   "/api/*": {
      "target": "http://localhost:3001"
   }
}

I am considering that your front end runs on PORT 3000 and you are making a request to PORT 3001 where your express server relies. 我正在考虑您的前端在PORT 3000上运行,并且您正在向快递服务器所依赖的PORT 3001发出请求。 After making the changes, kill the existing front end server and restart it. 进行更改后,请杀死现有的前端服务器并重新启动它。 Hot reloading wont update Package.json file. 热装不会更新Package.json文件。 Now all your request to /api/ will be directly routed to your PORT 3001 现在,您对/api/所有请求将直接路由到您的PORT 3001

If I understood you correctly, your front-end is running on localhost:3000 whereas backend running on local:3001, so you're looking for a solution to make request from front-end to back-end serving on 2 different ports? 如果我正确理解您的信息,那么您的前端运行在localhost:3000上,而后端运行在local:3001上,那么您正在寻找一种解决方案,以在2个不同的端口上进行从前端到后端的请求? If that so I believe you need to call your backend using the baseUrl, http:localhost:3001/api_call_here 如果是这样,我认为您需要使用baseUrl调用后端,http:localhost:3001 / api_call_here

        $.ajax({
          url: 'http:localhost:3001/api',
          type: 'post',
          data: $('form').serialize(),
          dataType: 'json',
          success: function(data) {
            console.log('successful ajax request made!');
          }
        });

You have to set up in your package.json this line: 您必须在package.json设置以下行:

"proxy": "http://localhost:PORT"

being PORT the port number you set up in your Express server. 作为PORT是您在Express服务器中设置的端口号。

Thus, Webpack local dev server knows which URL has to call to in order to reach your API run by Express. 因此,Webpack本地开发服务器知道必须调用哪个URL才能到达Express运行的API。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM