How can I export / import const app = express () to another file js

0

I am trying to separate responsibilities, sharing in different files and modules the different actions that I will carry out in my application on the server side.

I came across a problem, which I can not understand. I try to export from the file which starts the server, the variable app , in which I store express in the following way:

server.js

import express from 'express';
import webpack from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackConfig from '../webpack.config';
import path from 'path';

const app = express();

app.set('port', process.env.PORT || 3000);

app.use(webpackDevMiddleware(webpack(webpackConfig)));

app.get('*', (req, res) => { 
    res.sendFile(path.join(__dirname, '..', 'public', 'index.html'));
});

app.get('/api', (req, res) => {
    res.json({api: "Woks Fine"});
});

app.listen(app.get('port'), () => {
    console.log("App Start in Port", app.get('port'));
});

export default app;

apiGoogleMaps.js

import app from '../server.js';

export function respuestaMensaje(apiUrl, app) {
    console.log(apiUrl);
    app.post(apiUrl, (req, res) => {
        console.log(req.body);
    });
}

adress.js

import React, { Component } from 'react';
import { render } from 'react-dom';
import request from 'superagent';
import { respuestaMensaje } from '../../../src/handlers/apiGoogleMap.js';


class AddressInput extends Component{

    constructor(){    
        super();
        this.state = {
            address: "",
            api:"http://maps.google.com/maps/api/geocode/json?address=",
            direccion: "",
            latitud: "",
            longitud:""
        };
    } 

    render(){
        return(
            <div> 

                <form>                
                    <input type="text" value={this.state.address} onChange={this.updateAdress.bind(this)}/>
                    <button onClick={this.getAddressGeo.bind(this)}>Consultar</button> 
                </form>

                <ul>
                    <li><label>Direccion:</label>{this.state.direccion}</li>
                    <li><label>Latitud:{this.state.latitud}</label></li>
                    <li><label>Longitud:{this.state.longitud}</label></li>
                </ul>
            </div> 
        )
    }

    updateAdress(event){
        this.setState({
            address: event.target.value
        });
    }

    getAddressGeo(e){

        e.preventDefault();
        const apiUrl = this.state.api + this.state.address;
        respuestaMensaje(apiUrl);

    } 
}

export default AddressInput;

package.json

{
  "name": "reactnode",
  "version": "1.0.0",
  "description": "reactnodescaffold",
  "main": "index.js",
  "scripts": {
    "dev": "nodemon --exec babel-node src/server.js",
    "build:dev": "concurrently \"nodemon --exec babel-node src/server.js\" \"webpack --config webpack.config.js\""
  },
  "author": "PterPmntaM",
  "license": "ISC",
  "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.4",
    "babel-preset-env": "^1.6.1",
    "babel-preset-react": "^6.24.1",
    "concurrently": "^3.5.1",
    "css-loader": "^0.28.11",
    "es6-promise": "^4.2.4",
    "exports-loader": "^0.7.0",
    "extract-text-webpack-plugin": "^4.0.0-beta.0",
    "html-webpack-plugin": "^3.0.6",
    "imports-loader": "^0.8.0",
    "node-sass": "^4.7.2",
    "nodemon": "^1.17.2",
    "sass-loader": "^6.0.7",
    "style-loader": "^0.20.3",
    "webpack": "^4.1.1",
    "webpack-cli": "^2.0.13",
    "webpack-dev-middleware": "^3.0.1",
    "webpack-livereload-plugin": "^2.0.0",
    "whatwg-fetch": "^2.0.3"
  },
  "dependencies": {
    "express": "^4.16.3",
    "material-ui": "^1.0.0-beta.38",
    "react": "^16.2.0",
    "react-dom": "^16.2.0",
    "superagent": "^3.8.2"
  }
}

Project structure

The errors are many, but I know that it has to do with the import of the variable.

Errors that appear in console when I try to compile the web app.

    
asked by Pedro Miguel Pimienta Morales 28.03.2018 в 01:23
source

1 answer

0

I see some syntax error that could be the reason, to export a custom module the correct syntax is this according to official documentation:

exports.sayHelloInEnglish = function() {
 return "HELLO";
};

And to require a module I use it with:

var modulo = require('pathArchive');

It is possible anyway that you have other errors, in order I leave you that example.

Documentation link: link

Greetings

**** EDIT ****

//ARCHIVO APP.JS (principal)
//en este inicias express y configuras los set por ejemplo app.set(...)
var express = require('express');
var app = express();

//Aquí haces el llamado a tu custom module de rutas por ejemplo.
var router = require('../module-router.js');


app.get('*', function (req, res) {
  
   router.routeo(req, res);
  
});

app.listen(3000);
// -- FIN ARCHIVO PRINCIPAL



//ARCHIVO module-router.js
var routeo = function(req, res){

   switch(req.url){
   case '/home':
      //aqui lo que quieras que haga al llegar a /home
   break;
   case '/contact':
      //aqui lo que quieras que haga al llegar a /contact
   break;
   default:
      //aqui entrará todo lo que no cumpla con los cases ejemplo un 404
   
   }
  
}

//con module.exports es un objeto al que le dirás qué dunciones quieres que sean exportadas
module.exports = {

  routeo

}
// -- FIN ARCHIVO module-router.js

Therefore in this way what you will be doing is leaving all the routing of your app in a file being easier to understand the system, the same you do for each component.

I hope you can understand, remember that it is a simple example.

Greetings

    
answered by 29.03.2018 в 17:57