react-webpack-generators / generator-react-webpack

Yeoman generator for ReactJS and Webpack
http://newtriks.com/2013/12/31/automating-react-with-yeoman-and-grunt/
MIT License
2.88k stars 355 forks source link

Send ajax request from react component tol local handler. #289

Closed maddog2299 closed 7 years ago

maddog2299 commented 7 years ago

I am newbie in react + node js developing. For start learning this technologies I decided to use react-webpack-generator and I like it for simplicity. But I have a question. Can I send ajax query from react component to node.js handler? In browser I always get 404 error, but I dunno why, because my handler located in the same directory as my component.

Example of code :

setAjaxQuery(){
        $.ajax({
            type: 'POST',
            url: './fileHandler.js',
            success: function(){
               console.log('Success!')
            }.bind(this),
            error:  function(){
                console.log('Error!')
            }.bind(this)
        });
    }

render() {

    return (
      <div className="test-component">
            <button onClick={this.setAjaxQuery} value = "test" 
className="test-btn"ref="test">Test</button>
      </div>

    );
 }

Result in browser:

error

sthzg commented 7 years ago

Hi @maddog2299, React and Node are exciting technologies and I am glad you like the generator to explore them. Unfortunately this question is a bit too far away from what is supportable through the Github issue tracker, which is mostly about reporting bugs and feature suggestions.

It is not totally clear to me what fileHandler.js would do. If it has server-side responsibilities (which I assume since the question is to communicate with it through Ajax) I would suggest you take a look at existing NodeJS server-side frameworks like Express to setup a separate server with its own address on the backend-side.

This generator intentionally only provides the client-side setup and uses the webpack-dev-server to serve the assets created by Webpack during development. It is really only concerned with simple HTML, Javascript, and static assets (e.g. images) and not intended as a backend-server that would be capable of serving custom business logic.

IMO the easiest way to get started would be to serve fileHandler.js through a separate express server (or an equivalent library like Koa, etc.) and then using that server's address for the Ajax request.

sthzg commented 7 years ago

Hi @maddog2299, just wanted to get back to you if you have more questions regarding this issue or if it's okay for you if we close it.