React.js SyntaxError: Unexpected token < - javascript

I'm really new in react.js. I'm develop in Webstorm.
I have this error and I'm not succeed to solve it, it looks like the react is not recognize but i try to install any npm react package and is still not work..
SyntaxError: Unexpected token <
this is my code:
index.jsx:
/** #jsx React.DOM */
var React = require('react');
var ReactDOMServer = require('react-dom');
var DefaultLayout = require('./layout/Master');
//var element = React.createElement('div', null, 'Hello World!');
//console.log(ReactDOMServer.renderToString(element));
var CommentBox = ReactDOMServer.createClass({
render: function() {
return (
<div>
<h1>aslkdjaslkdj</h1>
</div>
//React.createElement('div', null, 'Hello World!')
);
}
});
module.exports = CommentBox;`var express = require('express');
index.js:
var express = require('express');
var router = express.Router();
var request = require('request');
router.get('/', function (req, res) {
//res.send("<h1> asdasasd </h1>");
res.render('index', {});
});
module.exports = router;
app.js:
var app = express();
var routes = require('./routes/index');
var path = require('path');
app.use('/', routes);
app.set('port', process.env.PORT || '5000');
// view engine setup
app.set('views', path.join(__dirname, '/views'));
app.set('view engine', 'jsx');
app.engine('jsx', require('express-react-views').createEngine());
app.use('/', routes);
module.exports = app;
var server = app.listen(app.get('port'), function(){
console.log("app started");
});`
package.json:
{
"name": "nodewithreactwithjsx",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Almog.h",
"license": "ISC",
"dependencies": {
"babel-preset-es2015": "^6.6.0",
"babel-preset-react": "^6.5.0",
"babel-register": "latest",
"express": "^4.13.4",
"express-react-views": "latest",
"react": "^15.0.2",
"react-dom": "^15.0.2"
},
"devDependencies": {
"babel-core": "^6.8.0",
"babel-loader": "^6.2.4",
"babel-preset-es2015": "^6.6.0",
"babel-preset-react": "^6.5.0",
"react": "^15.0.2",
"react-dom": "^15.0.2",
"webpack": "^1.13.0"
}
}

I think it is because your code has JSX - i.e. the HTML inside JavaScript part of CommentBox
To get JavaScript to run this you need to use a transpiler like Babel - this will turn a statement like:
<div className="apples">hello</div>
Into
React.createElement('div', {className:'apples'}, 'hello')
Javascript engines (like V8 in Chrome) cannot run JSX natively - they need transpiling first. I'm not sure how to get something like babel working in WebStorm though.

Related

Localhost/5000 not working. How do i get this ro work when i run node server.js

i have a problem, which when im trying to run my localhost/5000 its not working. I cant also get and post data on postman because of that. Anyone has an idea of how i can fix this ? However when i run the code it is showing that it is connected to my DB. I have also create an env file with the DB link and set the PORT to 5000
Here is the code:
server.js
const express = require('express')
const mongoose = require('mongoose')
const cors = require('cors')
const fileUpload = require('express-fileupload')
const cookieParser = require('cookie-parser')
const PORT = process.env.PORT || 5000
const app = express();
app.use(express.json())
app.use(cookieParser())
app.use(cors)
app.use(fileUpload({
useTempFiles: true
}))
//connect to db
const URI = process.env.MONGO_URL
mongoose.connect(URI,{
useCreateIndex: true,
useFindAndModify: false,
useNewUrlParser:true,
useUnifiedTopology:true
}, err=> {
if (err) throw err;
console.log('Connected to Mongo DB')
})
// app.get('/', (req, res) => {
// res.json({msg: "Welcome"})
// })
app.listen(PORT, () => {
console.log('Server is running on port', PORT)
})
app.use('/user', require('./routes/userRouter'))
package.json
{
"name": "Webapp",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"dev": "nodemon server.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"bcrypt": "^5.0.0",
"cloudinary": "^1.23.0",
"concurrently": "^5.3.0",
"cookie-parser": "^1.4.5",
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"express-fileupload": "^1.2.1",
"jsonwebtoken": "^8.5.1",
"mongoose": "^5.11.12"
},
"devDependencies": {
"nodemon": "^2.0.7"
}
}
app.listen() should be at end of file, after app.use()
Just use localhost:5000 instead of localhost/5000 for url

Web process failed to bind $port node

Heroku is ignoring my .env file for some reason, even though express shows what port to use and etc. I'm getting this error
Web process failed to bind to $PORT within 60 seconds
I read other solutions that talk about removing dotenv but if i do that, it will crash my app. I would need dotenv to get env variables, is there way i can set an .env for heroku or what would be the best solution to deploy a express + react + postgress application on heroku ?
here is my Profile
web: node app.js
app.js
var express = require('express');
var app = express();
var userRoute = require('./routes/users');
var postRoute = require('./routes/posts');
var bodyParser = require('body-parser');
var logger = require('morgan');
var session = require('express-session');
var cookieParser = require('cookie-parser') ;
var dotenv = require('dotenv');
var env = dotenv.config();
var cors = require('cors');
var models = require('./models/');
const PORT = process.env.PORT || 8000;
const passport = require('passport');
const path = require('path');
// const allowOrigin = process.env.ALLOW_ORIGIN || '*'
// CORS Middleware
if (!process.env.PORT) {
require('dotenv').config()
}
// console.log(process.env.DATABASE_URL);
if (!process.env.PORT) {
console.log('[api][port] 8000 set as default')
console.log('[api][header] Access-Control-Allow-Origin: * set as default')
} else {
console.log('[api][node] Loaded ENV vars from .env file')
console.log(`[api][port] ${process.env.PORT}`)
console.log(`[api][header] Access-Control-Allow-Origin: ${process.env.ALLOW_ORIGIN}`)
}
require('./config/passport-github');
require('./config/passport');
app.use(logger('dev'));
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'build')));
app.use(cookieParser());
app.use(session({
secret : process.env.JWT_SECRET,
saveUninitialized: false,
maxAge: 1000 * 60 * 60 * 84,
resave: false
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended:false}));
const isAuthenticated = function(req, res, next){
if(req.isAuthenticated()){
next();
console.log('this works');
}else{
res.redirect('http://127.0.0.1:8001/signIn');
}
}
// app.use(function(req, res, next) {
// res.header('Access-Control-Allow-Origin', '*');
// // res.header('Access-Control-Allow-Credentials', true);
// res.header("preflightContinue", false)
// // res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
// res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
// next();
// });
app.use(cors({
'allowedHeaders': ['Content-Type'], // headers that React is sending to the API
'exposedHeaders': ['Content-Type'], // headers that you are sending back to React
'origin': '*',
'methods': 'GET,HEAD,PUT,PATCH,POST,DELETE',
'preflightContinue': false
}));
app.use('/api/users', userRoute );
app.use('/api/posts', isAuthenticated, postRoute );
app.use(function(req, res, next) {
res.locals.user = req.user; // This is the important line
// req.session.user = user
console.log(res.locals.user);
next();
});
models.sequelize.sync().then(() => {
const server = app.listen(PORT, () => {
console.log(`Server is up and running on port ${PORT}`);
});
});
package.json
{
"name": "sequelize-demo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"client": "cd ./client && npm start ",
"server": "nodemon app.js",
"start": "concurrently --kill-others \"npm run client\" \"npm run server\" ",
"heroku-postbuild": "cd client && npm install && npm run build"
},
"author": "",
"license": "ISC",
"dependencies": {
"async": "^2.6.1",
"bcrypt": "^3.0.2",
"body-parser": "^1.18.3",
"concurrently": "^4.1.0",
"cookie-parser": "^1.4.3",
"cookie-session": "^2.0.0-beta.3",
"cors": "^2.8.5",
"crypto": "^1.0.1",
"dotenv": "^7.0.0",
"express": "^4.16.4",
"express-flash": "0.0.2",
"express-session": "^1.15.6",
"foreman": "^3.0.1",
"jsonwebtoken": "^8.4.0",
"morgan": "^1.9.1",
"nodemailer": "^5.1.1",
"nodemon": "^1.18.9",
"passport": "^0.4.0",
"passport-github": "^1.1.0",
"passport-github2": "^0.1.11",
"passport-jwt": "^4.0.0",
"passport-local": "^1.0.0",
"pg": "^7.8.0",
"pg-hstore": "^2.3.2",
"sequelize": "^4.42.0"
},
"devDependencies": {
"chai": "^4.2.0",
"mocha": "^6.1.2"
}
}
config/database.js
if (!process.env.PG_DB) {
const fs = require('fs')
const dotenv = require('dotenv')
const envConfig = dotenv.config({silent: true})
// for (var k in envConfig) {
// process.env[k] = envConfig[k]
// }
console.log('[api][sequelize] Loaded database ENV vars from .env file')
}
module.exports = {
development: {
username: process.env.POSTGRES_USER,
password: process.env.POSTGRES_PASSWORD,
database: process.env.POSTGRES_DB,
host: process.env.POSTGRES_HOST,
dialect: 'postgres',
migrationStorageTableName: 'sequelize_meta'
},
production: {
username: "root",
password: null,
database: "*******",
host: "127.0.0.1",
dialect: "postgres"
}
}
config/config.json
{
"development": {
"username": "eli",
"password": "",
"database": "elitest4",
"host": "127.0.0.1",
"dialect": "postgres"
},
"test": {
"username": "root",
"password": null,
"database": "database_test",
"host": "127.0.0.1",
"dialect": "postgres"
},
"production": {
"username": "root",
"password": null,
"database": "*******",
"host": "127.0.0.1",
"dialect": "postgres"
}
}
client/package.json
{
"name": "client",
"version": "0.1.0",
"private": true,
"dependencies": {
"#material-ui/core": "^3.9.1",
"#material-ui/icons": "^3.0.2",
"axios": "^0.18.0",
"history": "^4.7.2",
"http-proxy-middleware": "^0.19.1",
"jsonwebtoken": "^8.4.0",
"jwt-decode": "^2.2.0",
"material-ui-icons": "^1.0.0-beta.36",
"moment": "^2.24.0",
"react": "^16.7.0",
"react-dom": "^16.7.0",
"react-redux": "^6.0.0",
"react-router-dom": "^4.3.1",
"react-scripts": "2.1.3",
"redux": "^4.0.1",
"redux-thunk": "^2.3.0",
"superagent": "^4.1.0"
},
"scripts": {
"start": "PORT=8001 react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"postinstall": "react-scripts build"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": [
">0.2%",
"not dead",
"not ie <= 11",
"not op_mini all"
],
"devDependencies": {
"dotenv": "^6.2.0"
}
}
This is a simple oversight when deploying to Heroku. Heroku manages its own env vars to keep them safe. You should not be committing your .env to git or any version control. In Heorkus case simply go to the apps dashboard, in the settings tab and click reveal config vars and put the content of your dot env in the ui.
You can use the link bellow put your app name in there and you should see the settings screen.
https://dashboard.heroku.com/apps/<your_app_name>/settings

Connect express with react application

I want to create simple react app with express server.
I have setup simple express server like following.
package.json
{
"name": "hometask1",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^8.0.4",
"babel-preset-env": "^1.7.0",
"eslint": "^5.9.0",
"eslint-loader": "^2.1.1",
"express": "^4.16.4",
"jest": "^23.6.0",
"npm-run-all": "^4.1.3",
"open": "0.0.5",
"webpack": "^4.26.0",
"webpack-dev-middleware": "^3.4.0",
"webpack-hot-middleware": "^2.24.3"
},
"proxy": "http://localhost:3000/"
}
index.js
const express = require('express')
const app = express()
const port = 3000
//app.get('/', (req, res) => res.send('Hello World!'))
app.listen(port, () => console.log(`Listening on port ${port}!`))
app.get('/express_backend', (req, res) => {
res.send({ express: 'YOUR EXPRESS BACKEND IS CONNECTED TO REACT' });
});
I have folder structure like:
projectfolder
node_modules
index.html
index.js
package.json
package-lock.json
Now, i want to connect this express.js with my react app. Following is my react app. (I don't want to use create-react-app)
index.html
<!DOCTYPE html>
<html>
<head>
<title>Hello React</title>
<script src="https://unpkg.com/react#16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone#6.15.0/babel.min.js"></script>
</head>
<body>
<div id="root"></div>
</body>
<script type="text/babel">
var helloWorld = React.createElement("h1", {}, 'Hello World!');
class HelloWorld extends React.Component {
render () {
return (
<h1>Hello World!</h1>
)
}
}
const container = React.createElement("div", {}, helloWorld, <HelloWorld /> );
ReactDOM.render(container, document.getElementById('root'))
</script>
</html>
Any help would be greatly appreciated.
You need to serve your files from a public dir on base URL request (http://domain/)
1. Make css, jss files publicly accessible
Add this line to your express server file
const app = express()
const port = 3000
app.use(express.static('public')) // this line
2. Move index.html and index.js to public dir
You dir structure will look like
projectfolder
node_modules
public
index.html
index.js
package.json
package-lock.json
3. Add a route to serve the index file
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/public/index.html'));
});

Next Js & Babel causing infinite loop

So I got things working where it babel compiles everything, including next.js
I followed next.js docs on how to handle babel and created a .babelrc file:
{
"presets": ["next/babel", "es2015", "stage-0"]
}
When I run yarn run dev everything compiles and the server starts. When I load a page, next.js will run it's build process. Since things in the directory change, nodemon restarts the server and causes an infinite loop. Can some help me with this please???
This is my package.json file:
{
"name": "creatorsneverdie",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"scripts": {
"dev": "nodemon app.js --exec babel-node --ignore node_modules, .next, yarn.lock",
"build": "next build",
"start": "NODE_ENV=production node app.js"
},
"dependencies": {
"axios": "^0.16.2",
"bcrypt": "^1.0.2",
"body-parser": "^1.17.2",
"cors": "^2.8.4",
"cryptr": "^2.0.0",
"dotenv": "^4.0.0",
"express": "^4.15.3",
"express-session": "^1.15.4",
"lodash": "^4.17.4",
"lowdb": "^0.16.2",
"next": "^2.4.7",
"passport": "^0.3.2",
"passport-jwt": "^2.2.1",
"react": "^15.6.1",
"react-dom": "^15.6.1"
},
"devDependencies": {
"babel-cli": "^6.24.1",
"babel-loader": "^7.1.1",
"babel-preset-es2015": "^6.24.1",
"babel-preset-stage-0": "^6.24.1",
"nodemon": "^1.11.0"
}
}
And the app.js file:
import express from 'express'
import session from 'express-session'
import bodyParser from 'body-parser'
import cors from 'cors'
import passport from 'passport'
const db = require('./db/index.js').initDb()
const writeSeeds = require('./db/index.js').writeSeeds
const routes = require('./routes/index')
require('dotenv').config({path: 'variables.env'});
// Next config
const next = require('next')
const dev = process.env.NODE_ENV !== 'production'
const nextLoader = next({dev})
const handle = nextLoader.getRequestHandler()
nextLoader.prepare().then(() => {
const app = express();
app.use(cors());
app.set('db', db);
app.nextRender = nextLoader
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(session({
secret: process.env.SECRET,
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
require('./config/passport')(passport);
app.use('/', routes)
app.get('*', (req, res) => {
return handle(req, res)
})
// START APP
app.set('port', process.env.PORT || 1337);
if(!db.has('products').value()) {
writeSeeds(db);
}
const server = app.listen(app.get('port'), () => {
console.log(`Express running -> ${server.address().port}`)
});
})
I was having the same problem and I fixed that by adding "pages/"* to nodemon's ignore list. Somehow the build process is doing the pages source rewrite without changing anything which is then causing nodemon to restart and triggers the rebuild again.
Try to change your dev script to:
nodemon -w app.js --exec babel-node

Express server serves my static files but does not handle requests to my API. What is happening?

I built a small app on top of a company's API. I created my own API to interact with their's. My app uses React-Create-App to scaffold, with Redux, and the server is Experss/Node.js. It works totally fine on localhost but when I deploy it on Heroku, it serves the bundle but doesn't hand any user http requests to the server. It returns a 404 not found. Heroku gives no errors in their logs.
My post install script runs the build, which bundles the app. I have set environment port variable in the heroku dashboard as well.
package.json
{
"name": "event.me",
"version": "0.1.0",
"private": true,
"engines":{
"node": "7.2.1",
"npm": "3.10.10"
},
"dependencies": {
"axios": "^0.15.3",
"body-parser": "^1.17.1",
"express": "^4.15.2",
"moment": "^2.18.1",
"react": "^15.4.2",
"react-dom": "^15.4.2",
"react-progressbar.js": "^0.2.0",
"react-redux": "^5.0.3",
"react-router": "^3.0.0",
"react-router-dom": "^4.0.0",
"redux": "^3.6.0",
"redux-logger": "^3.0.0",
"redux-thunk": "^2.2.0"
},
"devDependencies": {
"eslint": "^3.18.0",
"eslint-config-airbnb": "^14.1.0",
"eslint-plugin-jsx-a11y": "^4.0.0",
"eslint-plugin-react": "^6.9.0",
"eslint-plugin-import": "^2.2.0",
"nodemon": "^1.11.0",
"react-scripts": "0.9.5"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject",
"server": "node server/server.js",
"postinstall": "npm run build"
}
}
server.js file
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const routes = require('./routes');
const app = express();
app.use(express.static(path.resolve(__dirname, '..', 'build')));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use('/api', routes);
const port = process.env.PORT || 8080;
app.listen(port, () => console.log(`Listening on ${port}`));
routes.js
const routes = require('express').Router();
const users = require('./controllers/users.js');
const events = require('./controllers/events.js');
routes.post('/sigin', users.signin);
routes.post('/signup', users.signup);
routes.get('/events', events.getAll);
routes.post('/events', events.attendEvent);
routes.delete('/events', events.flakeEvent);
routes.patch('/events', events.updateEvent);
routes.delete('/singleevent', events.deleteEvent);
routes.post('/createevent', events.createEvent);
module.exports = routes;
If you are using Create React App, one of the things you must do if you want Webpack to be used as proxy when calling your API is to set in your package.json:
...
"proxy": "http://localhost:3030",
...
Thus you use Webpack included in Create React App to proxy all the calls to your API and do not need an extra server.
For Heroku deployment you need to change localhost for Heroku URL and 3030 for your established port in Express server (process.env.PORT).
That's where I think the problem lies.
Also, you have to route your non API petitions to your index.html.
Add this to your server.js.
app.get('*', (req, res) => {
const way = path.join(__dirname, 'build', 'index.html');
res.sendFile(way);
});

Categories