node.js - Host React and Express on the same server? -


i working on react site has contact page. on contact page there text field enter message sent specific email address.

right i'm trying set express react app, only thing need express 1 feature.

in react app doing

$.post('http://localhost:3030/api',{value:'hi'}, function(result) {   console.log(result); }); 

and in express index.js file i'm doing

app.get('/api', (request, response) => {     console.log(request); }) 

just simple test see if things working properly.

when run these both , attempt execute post function, no 'access-control-allow-origin' header present on requested resource. error, saying can't make request separate domain. issue here not error, fact running express server , react app on 2 different servers.

is there way have them on same server? new back-end development, appreciated!

yes, react runs on client , express node.js framework. there's pretty chance you're using express if you're running boilerplate.

here's pretty walkthrough on more complete routing. https://medium.com/@patriciolpezjuri/using-create-react-app-with-react-router-express-js-8fa658bf892d

in several of applications routes this:

//router.js--and i'm positive react-express boilerplate var express = require('express'); var router = express.router();  /* home page. */ router.get('/', function(req, res, next) {   res.render('index', { title: 'express' }); });  const react =  (req, res, next)=>{   res.render('react', {      title: 'react application',     layout: false   }); };  router.get('/app', react); router.get('/app*', react); module.exports = router;  //app.js ... app.use('/', routes); //<--this exported router.  ... 

if want more simple like:

   let reactroute = (request, response, next) => {      //render react page you're doing that.     }    express.use('/api', yourapifunction)    express.use('/', reactroute)    express.use('/*', reactroute) //wildcards important if you're routing inside react. 

you can bypass things proxy tends more complex want. also--keep in mind don't have stick node on back-end if you're not comfortable it. react client side, use few production .net apps, php (lordy!), and, yes, lot of node servers.


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -