未捕获的TypeError:无法读取未定义的属性“post”

时间:2018-03-31 15:29:37

标签: javascript node.js express

我试图在不同的javascirpt文件中分隔我的代码,所以我有一个更好的顺序和这些分离的职责,但如果我使用app或'module.exports /导入import / export要求',我得到错误,它不允许我使用post, get等等。

apiGoogleMaps.js

const app = require('../server.js');

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

server.js

const express = require('express');
const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware');
const webpackConfig = require('../webpack.config');
const path = require('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;

adress.jsx(反应文件)

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;

1 个答案:

答案 0 :(得分:1)

您正在从apiGoogleMaps.js导出函数respuestaMensaje,但该函数未在server.js中的任何位置使用。要按照你想要的方式重构代码,我会做这样的事情 -

<强> server.js

var apiGoogleMaps = require('./apiGoogleMaps');
app.use(`/${apiUrl}`, apiGoogleMaps);

<强> apiGoogleMaps.js

var express       = require('express')
var router        = express.Router()
router.post('/', (req, res)=>{
 console.log(req.body)
})
module.exports = router;