The homepage loads ok in my ReactJSAPP, but when I click on any link it throws the following error. Since I am new to ReactJS, I am not sure which file I should check and fix this issue. Nodejs is working on port 4407
Folder Structure
Not Found
404
Error: Not Found
at /home/abc/public_html/ReactNode/app.js:46:13
at Layer.handle [as handle_request] (/home/abc/public_html/ReactNodeNew/node_modules/express/lib/router/layer.js:95:5)
Index.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;
My package.json is
{
"name": "frontend",
"version": "0.1.0",
"private": true,
"dependencies": {
"bootstrap": "^4.3.1",
"fixed-data-table": "^0.6.4",
"font-awesome": "^4.7.0",
"mysql": "^2.14.1",
"react": "^16.8.6",
"react-bootstrap": "^0.31.5",
"react-dom": "^16.8.6",
"react-redux": "^5.0.6",
"react-router": "^3.0.0",
"react-scripts": "3.0.0",
"redux": "^3.7.2"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"proxy": "http://localhost:4007",
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
And app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var users = require('./routes/users');
var app = express();
const port = process.env.PORT || 4007;
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
var mysql = require("mysql");
//Database connection
app.use(function(req, res, next){
res.locals.connection = mysql.createConnection({
host : '127.0.0.1',
user : 'nodejs',
password : '333365,',
database : 'nodejs',
port : '3306'
});
res.locals.connection.connect();
next();
});
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'frontend/build')));
app.use('/api', index);
app.use('/api/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname + '/frontend/build/index.html'))
})
var http = require('http');
module.exports = app;
var server = http.createServer(app);
server.listen(port);
Related
I've tried what feels like every answer on Stack Overflow regarding CORS and React, but I can't seem to get anything to work. I want to run React on localhost:3000 and Express on localhost:9090, then post some data from React to Express, and get back a message that says the server got the data.
I always get this error:
Access to fetch at 'http://127.0.0.1:9090/api' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
In my server I have two files involved in this:
api.js
var express = require("express");
var router = express.Router();
router.get('/', function(req, res, next) {
res.send("API is working properly");
});
router.post('/', function(req, res, next) {
console.log(req.body);
res.setHeader('content-type', 'application/json');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Origin", "http://localhost:3000");
res.send("result gotten!");
});
module.exports = router;
app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
// Require routes
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var apiRouter = require('./routes/api');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// Tell express to use specific routes
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/api', apiRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
In my client I have SchoolForm.js
import React, {Component} from "react";
class SchoolForm extends Component {
/* https://reactjs.org/docs/forms.html */
constructor(props) {
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
handleSubmit(event) {
console.log("Form was submitted with value " + this.state.value);
event.preventDefault();
const data = new FormData(this.current);
fetch('http://127.0.0.1:9090/api', {
method: 'POST',
body: data,
headers: {'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
"Access-Control-Allow-Methods": "DELETE, POST, GET, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With"},
})
.then(res => res.json())
.then(json => console.log(json))
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
School:
<input type="text" name="schoolName" value={this.state.value} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
export default SchoolForm;
I've also tried setting the proxy in my client's package.json:
{
"name": "maps-app",
"version": "0.1.0",
"private": true,
"proxy": "http://localhost:9090",
"dependencies": {
"#testing-library/jest-dom": "^5.11.9",
"#testing-library/react": "^11.2.5",
"#testing-library/user-event": "^12.8.1",
"leaflet": "^1.7.1",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-leaflet": "^3.1.0",
"react-scripts": "4.0.3",
"web-vitals": "^1.1.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
How do I get past this CORS block??
Install cors package
npm i --save cors
Then in your express app,
const app = express();
app.use(cors());
or else you can also add cors() to selected routes,
For example,
app.get('/', cors(), (req,res) => {})
Also you can pass cors options & configurations. To see available options please check the package - https://www.npmjs.com/package/cors
Note - If you need to add a proxy server for development process with create-react-app, try the manual approach.
I created a express app and having some big issues:
My routing is horrendous and can't get my 'Signin' and 'Signup' pages connecting to my home page. Some advice would be really helpful. (I've attached an image of my tree structure)
I'm also getting a error - throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn))
My app.js
// define dependencies
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var passport = require('passport');
var ejs = require('ejs');
var ExpressValidator = require('express-validator');
var LocalStrategy = require('passport-local').Strategy;
var multer = require('multer');
//handle file uploads
var upload = multer({des: './uploads'});
var flash = require('connect-flash');
var mongo = require('mongodb');
var mongoose = require('mongoose');
var db = mongoose.connection;
// const PORT = 5500; // you can change this if this port number is not available
const router = express.Router();
var routes = require('./routes/index');
var users = require('./routes/users');
// app.use('/', routes);
// app.use('/users', users);
var app = express();
//view engine setup
app.use('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'public')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
// Handle Sessions
app.use(session({
secret: 'secret',
saveUninitialized: true,
resave: true
}));
//passport middleware
app.use(passport.initialize());
app.use(passport.session());
//Express Validator middleware
app.use(ExpressValidator({
errorFormatter: function(param, msg, value){
var namespace = param.split('.'),
root = namespace.shift(),
formParam = root;
while(namespace.length){
formParam += '[' + namespace.shift() + ']';
}
return {
param : formParam,
msg : msg,
value : value
};
}
}));
//express messages middleware
app.use(require('connect-flash')());
app.use(function (req, res, next) {
res.locals.messages = require('express-messages')(req, res);
next();
});
//catch 404 and forward to error handler
app.use(function(req, res, next){
var err = new Error('Not Found');
err.status = 404;
next(err);
});
//error handlers
//development error handler
//will print stacktrace
if (app.get('env') === 'development'){
app.use(function(err, req, res, next){
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
//production erro handler
//no stacktraces leaked to user
app.use(function(err, req, res, next){
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
// //connect to database
// mongoose.connect('mongodb://localhost:27017/auth_tuts', { //replace this with you
// // useMongoClient: true
// }, (err, db) => {
// if (err) {
// console.log("Couldn't connect to database");
// } else {
// console.log(`Connected To Database`);
// }
// }
// );
module.exports = app;
My user.js
var express = require('express');
const router = express.Router();
// GET home page.
router.get('/', function (req, res, next) {
res.send('respond with a resource');
});
router.get('/signup', function (req, res, next) {
res.render('signup');
});
module.exports = router;
My index.js
var express = require('express');[enter image description here][1]
var router = express.Router();
// GET home page.
router.get('/', function(req, res, next){
res.render('index', { title: 'Express' });
});
module.exports = router;
my package.json file
{
"name": "project",
"version": "1.0.0",
"description": "College Project",
"main": "app.js",
"scripts": {
"start": "node ./bin/www"
},
"repository": {
"type": "git",
"url": "git+https://github.com/KevinKerin/kjs-webdesign.git"
},
"author": "Johnathan Munster",
"license": "ISC",
"bugs": {
"url": "https://github.com/KevinKerin/kjs-webdesign/issues"
},
"homepage": "https://github.com/KevinKerin/kjs-webdesign#readme",
"dependencies": {
"bcrypt": "^3.0.2",
"body-parser": "^1.18.3",
"connect-flash": "*",
"cookie-parser": "*",
"debug": "*",
"ejs": "^2.6.1",
"express": "^4.16.4",
"express-messages": "*",
"express-session": "^1.15.6",
"express-validator": "*",
"jsonwebtoken": "^8.4.0",
"mongodb": "*",
"mongoose": "^5.3.12",
"morgan": "*",
"multer": "*",
"nodemailer": "^4.6.8",
"nodemailer-smtp-transport": "^2.7.4",
"passport": "*",
"passport-http": "*",
"passport-local": "*",
"serve-favicon": "*",
"shortid": "^2.2.14"
}
}
File Structure
Issue fixed. I had .use instead of .set(‘views’, path...)
Working on my routing now.
I've deployed a React/Express app on Heroku. I'm using BrowserRouter. Everything worked fine locally. My issue is the backend routes are not working. The only route that works is the catchall route. The catchall route is also being called three times for some reason. I console logged the request path using 'req.path' to see which path was being called. It should have been '/google'. Instead the three calls give three different logs for req.path. They are: '/static/css/main.814455d3.chunk.css.map', '/static/js/main.06bdb7f0.chunk.js.map', '/static/js/1.1baafe13.chunk.js.map'. I'm hoping someone can help.
I've been stuck for over a day now. Here are my package.json and static.json from the client side:
static.json
{
"root": "build/",
"clean_urls": false,
"routes": {
"/**": "index.html"
}
}
package.json
{
"name": "workout_tracker",
"version": "0.1.0",
"private": true,
"dependencies": {
"axios": "^0.18.0",
"jw-paginate": "^1.0.2",
"jw-react-pagination": "^1.0.7",
"normalize.css": "^8.0.0",
"query-string": "^6.2.0",
"random-id": "0.0.2",
"react": "^16.5.2",
"react-dom": "^16.5.2",
"react-headroom": "^2.2.2",
"react-icons-kit": "^1.1.6",
"react-redux": "^5.0.7",
"react-router-dom": "^4.3.1",
"react-scripts": "^2.0.5",
"react-swipe-to-delete-component": "^0.3.4",
"react-swipeout": "^1.1.1",
"redux": "^4.0.0",
"redux-thunk": "^2.3.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
},
"devDependencies": {
"redux-devtools-extension": "^2.13.5"
},
"proxy":"localhost:4000",
"browserslist": [
">0.2%",
"not dead",
"not ie <= 11",
"not op_mini all"
]
}
And this is my package.json from express
{
"name": "expresstest",
"version": "1.0.0",
"description": "app to test express and mysql",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start":"node app.js",
"heroku-postbuild": "cd client && npm install && npm run build"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.18.3",
"connect-flash": "^0.1.1",
"cookie-session": "^2.0.0-beta.3",
"cors": "^2.8.4",
"express": "^4.16.3",
"mysql": "^2.16.0",
"passport": "^0.4.0",
"passport-google-oauth20": "^1.0.0"
}
}
This is part of the code from the server. I omitted the other routes as none besides the catchall route are being called anyway.
let express = require("express");
let cors= require("cors");
let mysql = require("mysql");
const util = require("util");
const keys = require("./config/keys");
const passport = require("passport");
const passportSetup = require("./config/passport-setup");
const bodyParser = require("body-parser");
const flash= require("connect-flash");
const path= require("path");
console.log("process env");
console.log("-------");
console.log(process.env.PWD);
const cookieSession = require("cookie-session");
let app = express();
app.use(bodyParser.json());
app.use(cookieSession({
maxAge:24 * 60 * 60 * 1000,
keys:[keys.session.cookieKey]
}));
app.use(passport.initialize());
app.use(passport.session());
if (process.env.NODE_ENV === 'production') {
console.log("inside prod");
app.use(express.static('client/build'));
}
let connection =keys.connection;
app.get("/google", passport.authenticate("google",{
scope:['profile'],
failureFlash:"failure"
}),(req,res)=>{
// console.log(req.flash());
console.log("/google route");
});
const port = process.env.PORT || 4000;
let http = require("http");
let server = http.createServer(app,(req,res)=>{
res.writeHead(200, {"Access-Control-Allow-Origiin": "*"})
});
app.get('/*', (req, res) => {
console.log("catchall");
console.log(req.hostname);
console.log(req.path);
console.log(path.join(__dirname + '/client', 'build', 'index.html'));
res.sendFile(path.join(__dirname + '/client', 'build', 'index.html'));
})
server.listen(port, ()=>{
console.log("Listening on "+ port)
});
Here is my folder structure:
Link to pic of my folder structure
EDIT: I got it working, here is the code that works. I don't know why it works, though. I just tried some things I found on blogs for React/Express/Heroku projects. If anyone can tell me why it works it would be greatly appreciated.
let express = require("express");
let cors= require("cors");
let mysql = require("mysql");
const util = require("util");
const keys = require("./config/keys");
const passport = require("passport");
const passportSetup = require("./config/passport-setup");
const bodyParser = require("body-parser");
const flash= require("connect-flash");
const path= require("path");
console.log("process env");
console.log("-------");
console.log(process.env.PWD);
const cookieSession = require("cookie-session");
let app = express();
app.use(bodyParser.json());
app.use(express.static(__dirname));
app.use(cookieSession({
maxAge:24 * 60 * 60 * 1000,
keys:[keys.session.cookieKey]
}));
app.use(passport.initialize());
app.use(passport.session());
if (process.env.NODE_ENV === 'production') {
console.log("inside prod");
app.use(express.static('client/build'));
}
let connection =keys.connection;
app.get("/google", passport.authenticate("google",{
scope:['profile'],
failureFlash:"failure"
}),(req,res)=>{
// console.log(req.flash());
console.log("/google route");
});
const port = process.env.PORT || 4000;
let http = require("http");
let server = http.createServer(app,(req,res)=>{
res.writeHead(200, {"Access-Control-Allow-Origiin": "*"})
});
app.get("/service-worker.js", (req, res) => {
res.sendFile(path.join(__dirname + "/client","build", "service-worker.js"));
});
app.get('/*', (req, res) => {
console.log("catchall");
console.log(req.hostname);
console.log(req.path);
console.log(path.join(__dirname + '/client', 'build', 'index.html'));
res.sendFile(path.join(__dirname + '/client', 'build', 'index.html'));
})
server.listen(port, ()=>{
console.log("Listening on "+ port)
});
I am going through the Manning Getting MEAN book. I want to use bootstrap sass and have loaded bootstrap-loader. When I run nodemon I get the following error:
/Users/mglaz/Projects/mean/theCMF/node_modules/bootstrap/dist/js/bootstrap.js:8
throw new Error('Bootstrap\'s JavaScript requires jQuery')
here's my app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
require('jquery');
require('bootstrap');
require('bootstrap-loader');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
and my package.json
{
"name": "loc8r",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www"
},
"dependencies": {
"body-parser": "~1.8.1",
"cookie-parser": "~1.3.3",
"debug": "~2.0.0",
"express": "~4.9.0",
"jquery": "^3.1.1",
"morgan": "~1.3.0",
"pug": "^2.0.0-beta6",
"serve-favicon": "~2.1.3"
},
"devDependencies": {
"bootstrap": "^4.0.0-alpha.4",
"css-loader": "^0.26.1",
"exports-loader": "^0.6.3",
"extract-text-webpack-plugin": "^1.0.1",
"file-loader": "^0.9.0",
"imports-loader": "^0.7.0",
"node-sass": "^3.13.1",
"postcss-loader": "^1.2.0",
"resolve-url-loader": "^1.6.1",
"sass-loader": "^4.0.2",
"style-loader": "^0.13.1",
"url-loader": "^0.5.7",
"webpack": "^1.14.0"
}
}
Have a look at jQuery not define in bootstrap module and http://blog.npmjs.org/post/112064849860/using-jquery-plugins-with-npm
You need to set the global jQuery variable
global.jQuery = require('jquery');
require('bootstrap');
My package.json
{
"name": "lays-vroubek",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "supervisor ./bin/www"
},
"dependencies": {
"body-parser": "~1.13.2",
"cookie-parser": "~1.3.5",
"debug": "~2.2.0",
"express": "~4.13.1",
"jade": "~1.11.0",
"less-middleware": "^2.0.1",
"morgan": "~1.6.1",
"reload": "^0.7.0",
"serve-favicon": "~2.3.0",
"supervisor": "^0.9.1"
}
}
My app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var lessMiddleware = require('less-middleware');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(lessMiddleware(path.join(__dirname, 'public'), {
force: true,
debug: true,
once: false
}));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
I run my app with comand: "$ DEBUG=lays-vroubek:* npm start" but auto-reload does not work without any error msg (app runs)
lays-vroubek#0.0.0 start /Users/jan.michalik/Workspace/Sites/lays-vroubek
supervisor ./bin/www
Running node-supervisor with
program './bin/www'
--watch '.'
--extensions 'node,js,/bin/www'
--exec 'node'
Starting child process with 'node ./bin/www'
Watching directory '/Users/jan.michalik/Workspace/Sites/lays-vroubek' for changes.
Press rs for restarting the process.
lays-vroubek:server Listening on port 3000 +0ms
Any help?
For example, you have an express app named backend. Than you can use
DEBUG=backend:* supervisor -w server -e ejs,js,json bin/www
to autorestart express app if any of ejs, js or json files is changed inside server dir (usual, i place my express app into server dir)