简体   繁体   中英

POST request from react child component in express

I am using the MERN stack (With react-router and redux) for my program. In my application, I have a <Navbar /> component as well as a <SearchBar> component.

I used create-react-app to handle the react side of things, and as i'm sure you all know, everything is ultimately contained within App.js Within App.js, Navbar is outside of the react router switch statement like so.

 <Provider store={store}>
  <Router>
    <div>
   <NavBarContainer />
   <Switch>  
      <Route exact path="/" component={Homepage} />
      <Route exact path="/ProfilePage" component={ProfilePageContainer} />   
      <Route exact path="/SearchPage" component={SearchPageContainer} />     
      <Route exact path="/LoginPage" component={LoginContainer} />
   </Switch>
 </div>
 </Router>
 </Provider>

My problem is that SearchBar is a child component of Navbar like so.

class Navbar extends Component {
  render(){
    return (
    ***navbar stuff
    {this.props.loggedIn && <SearchBar />} 
    ***navbar stuff
    )
  }
}

And when I try to make a POST request from <SearchBar /> like this:

addSearch = (event) => {
  if(this.props.loggedIn){
    fetch('/api/SearchPage', {
      headers : {
        "Accept" : "application/json",
        "Content-Type" : "application/json"       
      },
      method :  'POST',
      body : JSON.stringify({
        username : this.props.username,
        search : this.search.value
      }).then(function(value){
        return value.json()})
      .then(function(data){
        console.log("SearchData", data)
      }).bind(this) 
    })
  }
}

Where addSearch() is called within the SearchBar with onClick(this.addSearch) .

When I do this, the POST request comes from whatever page is rendered under my Navbar !

My page says: Cannot POST /api/[Pagename}.js

Whatever page is currently rendered under Navbar with react switch will replace [Pagename]

How can I make <SearchBar /> create a POST request within itself? Or, if that is not possible, how can I contain that post request within the <Navbar> component?

Something I'm considering, is that it has something to do with the fact hat I'm using a body parser, and the current body of the page happens to be whatever page is loaded. However, I seem to define the body: within the POST request so this doesn't make much sense.

For now, i'm simply going to put all of the code and logic of the <SearchBar> component within the <Navbar> and the search page, but I suspect that there is a much better way to do this (while leaving <SearchBar> within its own component). Ideally, I'd like to send a POST request just from <SearchBar> .

I know I'm probably missing something common here.

Here is the endpoint in the express file (It is just set up for testing)

```
 app.post('/api/SearchPage', function(req, res done){  
  if(err) done(err);
  done(null, res.json({"Test" : "testobj"}))
}'
```   

From the given code, it seems like its the url in fetch() that is the issue here. Since you are only stating '/app/SearchPage' , then it is assumed to be part of the React app (which it is not, since its should hit your API endpoint).

You should try to insert the url for the endpoint. Is is sometimes running on a different port than the React application (depending on your setup). Endpoint could be something like http://localhost:3050/api/SearchPage , which should be set in the URL parameter of your fetch() method.

I took a break today but the answer seems obvious at the moment. When I do fetch(), all react does is append the URL (in this case /API/Page) to localhost/[pageimon] Because all of my routing is handled client side by react router, my URL is whatever page I'm on. (I did not do any routing with express). Since the navbar is out side of all switching (on purpose), whatever is contained in there will not make a successful post request, as all fetch calls will simply read the URL.

So I have to figure out a way to either bypass this (possibly a fetch parameter, or a react middleware module).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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