Проблема в развертывании Front End и Backend в одном приложении в Heroku - PullRequest
0 голосов
/ 28 мая 2019

Сегодня я научился развертывать свое приложение React в Heroku.Мое приложение в основном представляет собой одностраничное приложение, которое имеет некоторый компонент и одну форму обратной связи, куда я отправляю отзывы посетителей в базу данных.Для этого я создал REST API, который отправляет отзыв.API отдыха создается с использованием экспресс-маршрутизаторов и mongodb для целей базы данных.

Теперь я развернул свое приложение на heroku через github.и все, кажется, работает нормально, но когда я отправляю некоторые отзывы, это не работает, так как я думаю, что server.js не запускает сервер, так как package.json не может найти server.js для запуска сервера.Я хочу развернуть интерфейс и бэкэнд на одном сервере.Это возможно и как?Пожалуйста, помогите мне.

Я попытался включить "node server.js" в мой package.json, чтобы он работал, но не успешно.Также я думаю о создании отдельного приложения для подключения к серверу.

Вот структура папок моего приложения:

enter image description here

вот мой package.json:

{
 "name": "cocina_sitio",
 "version": "1.0.0",
 "description": "",
 "private": true,
 "main": "index.js",
 "scripts": {
   "start": "react-scripts start",
   "build": "react-scripts build",
   "test": "react-scripts test",
   "eject": "react-scripts eject"
 },
 "author": "",
 "license": "ISC",
 "dependencies": {
   "body-parser": "^1.19.0",
   "bootstrap": "^4.3.1",
   "express": "^4.17.0",
   "google-maps-react": "^2.0.2",
   "jquery": "^3.4.1",
   "mongoose": "^5.5.10",
   "morgan": "^1.9.1",
   "popper.js": "^1.14.7",
   "react": "^16.8.4",
   "react-bootstrap": "^1.0.0-beta.5",
   "react-dom": "^16.8.4",
   "react-router": "^5.0.0",
   "react-router-dom": "^5.0.0",
   "react-scripts": "^2.1.8",
   "reactstrap": "^7.1.0"
 },
 "browserslist": [
    ">0.2%",
    "not dead",
    "not ie <= 11",
    "not op_mini all"
 ],
  "devDependencies": {}
}

и server.js:

const http = require('http');
const app = require('./backend_connectivity/app.js');
const port = process.env.PORT || 4000;
const server = http.createServer(app);
server.listen(port);

и feedback.js:

import React, {Component} from 'react';
import {
    Jumbotron,
    Button,
    Container,
    Form,
    Row,
    Col
} from 'react-bootstrap';

import './style/style-parallex.css';

class Feedback extends Component {
    constructor(props) {
        super(props);
        this.state= {
            user: {
                Name: '',
                Email: '',
                Message: ''
            },
            submitted: false
        }
        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

handleChange(event) {
    const {name, value} = event.target;
    const {user} = this.state;
    this.setState({
        user: {
            ...user,
            [name]:value
        }
    })
}

handleSubmit(event) {
    event.preventDefault();
    this.setState({submitted: true});
    const {user} = this.state;
    const URL = "http://localhost:4000/signup";   // ----> this is in case of locally. Dontknow if this should change in case of Heroku
    const data = JSON.stringify({
        name: user.Name,
        email: user.Email,
        message: user.Message
    });
    const otherParam= {
        mode: 'cors',
        headers: {
            'Accept': 'application/json, text/plain, */*',
            "Content-Type": "application/json"
        },
        body: data,
        method: 'POST'
    }
    fetch(URL, otherParam)
        .then(data => data.json())
        .then(data => console.log(data))
        .catch(err => console.log(err));
}

    render() {
        const {user,submitted} = this.state;
        return(
            <React.Fragment>

                <Jumbotron fluid style={{height: 500, background: '#38507d45'}} id="feedbackform">
                    <Container style={{display: 'flex', justifyContent: 'center', alignItems: 'center'}}>                    
                        <h1 style={{color: 'white', textDecorationColor: 'white'}}>feedback are always welcome</h1>
                    </Container>
                    <Container>
                        <Form onSubmit={this.handleSubmit}>
                            <Row>
                                <Col>
                                    <Form.Group controlId="Name" className={(submitted && !user.name ? 'has-error' : '')}>
                                        <Form.Label>Name</Form.Label>
                                        <Form.Control type="text" name="Name" id="Name" placeholder="Your Name" onChange={this.handleChange}/>
                                    </Form.Group>
                                </Col>
                                <Col>
                                    <Form.Group controlId="Email" className={(submitted && !user.email ? 'has-error' : '')}>
                                        <Form.Label>Email address</Form.Label>
                                        <Form.Control type="email" placeholder="Your email" name="Email" id="Email" onChange={this.handleChange}/>
                                        <Form.Text className="text-muted">
                                            We'll never share your email with anyone else.
                                        </Form.Text>
                                    </Form.Group> 
                                </Col>
                            </Row>
                            <Form.Group controlId="ControlTextarea" className={(submitted && !user.message ? 'has-error' : '')}>
                                <Form.Label>Message</Form.Label>
                                <Form.Control as="textarea" rows="5" placeholder="Your Message" name="Message" id="Message" onChange={this.handleChange}/>
                            </Form.Group>
                            <Button variant="primary" type="submit" style={{float: 'right'}}>
                                Submit
                            </Button>
                        </Form>
                    </Container>
                </Jumbotron>
            </React.Fragment>
        );
    }
}

export default Feedback;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...