我在寫一個React應用程序,它現在狀態良好。現在,我想添加一個後端來訪問Mongodb文檔並創建一個REST API,就像在現有項目的頂部添加一個圖層一樣。我希望Express可以在相同端口上收聽我的React應用程序。我正在使用Gulp,使用其默認任務啓動應用程序。如何使用Gulp將Express添加到React應用程序?
我找不到一種方法來做到這一點,如果app.listen
使用相同的端口作爲它的反應部分,我得到port already in use
(顯然)。
這裏是我的gulpfile.js
"use strict";
var gulp = require('gulp'),
connect = require('gulp-connect'),
open = require('gulp-open'),
browserify = require('browserify'),
reactify = require('reactify'),
source = require('vinyl-source-stream'),
eslint = require('gulp-eslint'),
http = require('http'),
concat = require('gulp-concat');
var config = {
port: process.env.PORT || 1991,
devBaseUrl: 'http://localhost',
paths: {
html: './src/*.html',
js: './src/**/*.jsx',
css: './public/stylesheets/**/*.css',
dist: './dist',
mainJs: './src/main.jsx'
}
};
//start a local dev server
gulp.task('connect', function() {
connect.server({
root: ['dist'],
port: config.port,
base: config.devBaseUrl,
livereload: true
});
});
gulp.task('open', ['connect'], function() {
gulp.src('dist/index.html')
.pipe(open({uri: config.devBaseUrl + ':' + config.port + '/'}));
});
gulp.task('html', function() {
gulp.src(config.paths.html)
.pipe(gulp.dest(config.paths.dist))
.pipe(connect.reload());
});
gulp.task('js', function() {
browserify(config.paths.mainJs)
.transform(reactify)
.bundle()
.on('error', console.error.bind(console))
.pipe(source('bundle.js'))
.pipe(gulp.dest(config.paths.dist + '/scripts'))
.pipe(connect.reload());
});
gulp.task('css', function() {
gulp.src(config.paths.css)
.pipe(concat('bundle.css'))
.pipe(gulp.dest(config.paths.dist + '/css'))
.pipe(connect.reload());
});
gulp.task('lint', function() {
return gulp.src(config.paths.js)
.pipe(eslint({configFile: 'eslint.config.json'}))
.pipe(eslint.format());
});
gulp.task('watch', function() {
console.log('Files have been changed... Reloading...');
gulp.watch(config.paths.html, ['html']);
gulp.watch(config.paths.css, ['css']);
gulp.watch(config.paths.js, ['js']);
});
gulp.task('default', ['html', 'js', 'css','lint', 'open', 'watch']);
這可能嗎?如果是這樣,我該怎麼做?
當你說「我想添加一個後端Express」時,你的意思並不完全清楚。你後端的目標是什麼?它看起來像你已經有吞吐任務,啓動一個簡單的服務器,並生活重新加載文件的變化。你想要快遞服務器做什麼? –
我想添加一個REST API並管理mongodb文檔。 是的,該應用程序狀態良好,但它只是一個前端應用程序。關鍵是我希望它是一個完整的應用程序。 – Hideya
好的。你打算主持這個項目的計劃是什麼? AWS? Digital Oceaen上的專用服務器/微滴? Azure的? –