React front end with Node express back end. Terminal crashes every time I make a change - node.js

I am building my first application using a React Front end and a node.js backend with express. I followed this guide https://levelup.gitconnected.com/how-to-render-react-app-using-express-server-in-node-js-a428ec4dfe2b to set up the bones of the app. To be honest I am not quite sure what code to include so I will include everything I think is necessary. The issue is every time I make a change, the terminal crashes and I am forced to restart the process.
In previous tutorials I set up the server on a different port then ran nodemon to update every time changes were made. I have watched 10+ hours of videos and have read countless articles on how to use node/express but I cant seem to get past the initial setup without something going completely wrong and having to try and find a new tutorial. I am newer to Node and very new to express so any constructive knowledge is appreciated. Thank you!
index.js
const express = require("express");
const app = express(); // create express app
// add middleware
const path = require("path");
// as the build folder will be created inside react-app folder, we are creating a path for the build folder located outside the server folder. must go first!!
app.use(express.static(path.join(__dirname, "..", "build")));
app.use(express.static("public"));
// start express server on port 5000
app.listen(5000, () => {
console.log("server started on port 5000");
});
package.json
{
"name": "react-app",
"version": "0.1.0",
"private": true,
"dependencies": {
"#testing-library/jest-dom": "^5.16.5",
"#testing-library/react": "^13.4.0",
"#testing-library/user-event": "^13.5.0",
"axios": "^1.3.3",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4",
"express": "^4.18.2",
"mongodb": "^5.0.1",
"mongoose": "^6.9.1",
"morgan": "^1.10.0",
"nodemon": "^2.0.20"
},
"scripts": {
"start-client": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"start": "yarn run build && (cd server && yarn start)"
},
"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"
]
}
}
app.js. example code comment down is from the explanation on how to insert data using express.
import React from "react";
import axios from "axios";
import "./styles.css";
import DayContainer from './views/dayContainer/dayContainer'
import Header from './views/Header/header';
import Form from "./views/Form/form";
export default class App extends React.Component {
state = {
users: [],
};
componentDidMount() {
axios.get("/users.json").then((response) => {
this.setState({ users: response.data });
});
}
render() {
const { users } = this.state;
return (
<div className="App">
<Header/>
<div className='module-container'>
<DayContainer/>
<Form/>
</div>
{/* example code */}
<div>
<ul className="users">
{users.map((user) => (
<li className="user">
<p>
<strong>Name:</strong> {user.name}
</p>
<p>
<strong>Email:</strong> {user.email}
</p>
<p>
<strong>City:</strong> {user.address.city}
</p>
</li>
))}
</ul>
</div>
</div>
);
}
}
I have used multiple different tutorials using different methods of setting up express. I think this issue might stem from the fact that both the server and front end are using the same port but I could be wrong.
EDIT: adding server.json
{
"name": "express-static-serve",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"start": "nodemon index.js"
},
"license": "MIT",
"dependencies": {
"express": "^4.18.2",
"nodemon": "^2.0.20"
}
}
Error :
Terminal exits with error code 2
Evey time I change something then refresh the app. I need to press ctrl + c to exit the process and then I get error code 2 and the terminal closes

That's a pretty convoluted way to set up react, and probably not what will want when you go to production. The best way is to have the react app use a proxy to redirect it to the main server. Here's how to do it: https://create-react-app.dev/docs/proxying-api-requests-in-development/
Basically you just add a "proxy" property to the react app's package.json and point to the URL of the node server. If that doesn't work you can configure the proxy manually (https://create-react-app.dev/docs/proxying-api-requests-in-development/#configuring-the-proxy-manually).
I've never understood why the developers of react made it so complicated as having to run two separate servers just to develop an app, when in production, it's only one server. But I've found it is one of the pain points for newcomers into the react world. Hopefully the instructions there will be of more help.
If you do this, you don't need two app.static entries in your server's index.js.

Related

Error with react testing library and create react app (SyntaxError: Unexpected identifier import ArrayFrom from "./polyfills/array.from.mjs";)

I know when you have a bare React app, you config webpack to use babel and then jest is using the babel configuration to compile the modules.
Now I have an app created with create-react-app. With a package.json as follows:
{
"name": "it does not matter",
"version": "0.1.0",
"private": true,
"dependencies": {
"react": "^16.2.0",
"react-dom": "^16.2.0",
"react-redux": "^7.2.0",
"react-redux-loading": "^1.0.1",
"react-router-dom": "^5.1.2",
"react-scripts": "1.1.1",
"redux": "^4.0.5",
"redux-thunk": "^2.3.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
}
}
With things being like that I wrote the simplest possible test, that passes as green:
import React from "react";
import ReactDOM from "react-dom";
it("renders LoggedUser without crashing", () => {
const div = document.createElement("div");
const name = "::name::";
const avatarURL = "::avatarURL::";
const loggedUser = { name, avatarURL };
ReactDOM.render(<LoggedUser loggedUser={loggedUser} />, div);
});
Now I follow the create react app docs to add the React testing library:
https://create-react-app.dev/docs/running-tests/#option-2-react-testing-library
I follow the steps but when running the test it complaints:
import React from "react";
import { render } from "#testing-library/react";
import { LoggedUser } from "../components/LoggedUser";
it("renders LoggedUser without crashing", () => {
const name = "::name::";
const avatarURL = "::avatarURL::";
const loggedUser = { name, avatarURL };
render(<LoggedUser loggedUser={loggedUser} />);
});
import ArrayFrom from "./polyfills/array.from.mjs";
^^^^^^^^^
SyntaxError: Unexpected identifier
In my package I have only added the dependencies:
"devDependencies": {
"#testing-library/jest-dom": "^5.5.0",
"#testing-library/react": "^10.0.4"
}
And as the docs suggested created a src/setupTests.js file
// react-testing-library renders your components to document.body,
// this adds jest-dom's custom assertions
import '#testing-library/jest-dom/extend-expect';
I have tried many things (a .babelrc file with and without a jest.config file...) but I was unable to make the test pass, when fixing one problem another one appeared...
Maybe sb is familiar with this problem and its possible solutions.
Cheers!
Well, in the end what I was trying to do was very twisted because I didn't know very well the webpack-babel-jest delegation when using the create-react-app boilerplate...
So I made another app from scratch and it did work, so I just updated in my real app the "react-scripts": "3.x.x" to make it work.
I apologize for all this hassle, anyway digging in the boilerplate was quite educational.
Thank you anyway!

Change in file does not trigger reload of Node server

Windows 10, VS Code, Node 10.16.2.
I have a small project that only contains a few files - index.js and a css file mainly.
npm start starts the project and a message says Server will reload automatically if you modify any file!
This works if I modify the css file for example. But if I modify the index.js file nothing happens.
My Node setup is default. I have not manually installed any modules to watch for file changes and I don't want to. Just trying to figure out why this doesn't work for the js file.
EDIT
Below is the contents of package.json. Something else interesting is that if I allow index.js to be linted I get a weird error about the equals sign after propTypes. Someone suggested might be an issue with webpack, which I know nothing about. But they said if the file won't build because of an error then a change in the file might not be detected. Note, though, that the project runs fine.
static propTypes = {
width: PropTypes.number,
height: PropTypes.number
};
Here is package.json:
{
"private": true,
"name": "some name",
"description": "some description",
"version": "0.1.0",
"scripts": {
"start": "nr1 package:serve",
"test": "exit 0"
},
"nr1": {
"uuid": "e13bf28f-8989-4a3a-832c-7c3f0eec6c3e",
"sdkVersion": 2
},
"dependencies": {
"prop-types": "^15.6.2",
"react": "^16.6.3",
"react-dom": "^16.6.3"
},
"browserslist": [
"last 2 versions",
"not ie < 11",
"not dead"
],
"devDependencies": {
"eslint": "^6.1.0",
"eslint-plugin-react": "^7.14.3"
}
}

Vue.js stuck on serving at 40% how to recover?

I decided to delete the node modules folder, do a npm install then do a npm run serve it always gets stuck around 40% and stays there forever. When done from the UI it also gets stuck on a similar amount:
$ vue-cli-service serve --open --mode development --https --dashboard
INFO Starting development server...
40% building 118/134 modules 16 active
...tApp\node_modules\axios\lib\defaults.js
another time:
40% building 134/147 modules 13 active
...\node_modules\axios\lib\adapters\xhr.js
I notice Node.js process is constantly going at around 15%, but nothing happens if I wait and wait and wait.
Package.json
{
"name": "myapp",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint",
"test:e2e": "vue-cli-service test:e2e",
"test:unit": "vue-cli-service test:unit"
},
"dependencies": {
"#aspnet/signalr": "^1.1.4",
"axios": "^0.18.0",
"vue": "^2.6.10",
"vue-axios": "^2.1.4",
"vue-router": "^3.0.6",
"vuex": "^3.1.1"
},
"devDependencies": {
"#vue/cli-plugin-babel": "^3.7.0",
"#vue/cli-plugin-e2e-cypress": "^3.7.0",
"#vue/cli-plugin-eslint": "^3.7.0",
"#vue/cli-plugin-unit-jest": "^3.7.0",
"#vue/cli-service": "^3.7.0",
"#vue/eslint-config-standard": "^4.0.0",
"#vue/test-utils": "^1.0.0-beta.20",
"babel-core": "7.0.0-bridge.0",
"babel-eslint": "^10.0.1",
"babel-jest": "^23.6.0",
"eslint": "^5.16.0",
"eslint-plugin-vue": "^5.2.2",
"node-sass": "^4.12.0",
"sass-loader": "^7.1.0",
"vue-template-compiler": "^2.6.10"
},
"eslintConfig": {
"root": true,
"env": {
"node": true
},
"extends": [
"plugin:vue/essential",
"#vue/standard"
],
"rules": {
"space-before-function-paren": [
"error",
{
"anonymous": "always",
"named": "always",
"asyncArrow": "always"
}
],
"keyword-spacing": [
"error",
{
"after": true
}
],
"semi": [
"error",
"always"
],
"indent": "off",
"vue/script-indent": [
"warn",
2,
{
"baseIndent": 1
}
]
},
"parserOptions": {
"parser": "babel-eslint"
}
},
"postcss": {
"plugins": {
"autoprefixer": {}
}
},
"browserslist": [
"> 1%",
"last 2 versions",
"not ie <= 8"
],
"jest": {
"moduleFileExtensions": [
"js",
"jsx",
"json",
"vue"
],
"transform": {
"^.+\\.vue$": "vue-jest",
".+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$": "jest-transform-stub",
"^.+\\.jsx?$": "babel-jest"
},
"moduleNameMapper": {
"^#/(.*)$": "<rootDir>/src/$1"
},
"snapshotSerializers": [
"jest-serializer-vue"
],
"testMatch": [
"**/tests/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)"
],
"testURL": "http://localhost/"
}
}
$ node --version v10.15.3
How do I recover from this?
Update:
There is something magic about the number 40, I removed all mentions of Axios and now I still get stuck at 40% but with a different thing:
40% building 133/146 modules 13 active
...abel\runtime-corejs2\core-js\promise.js
In my case:
It was an error into the template.
Make sure there is a container tag just after
<template><container_tag> ... your code ...</container_tag></template> it could be as simple as a <div>
Try running npm run lint and see if you've got some errors in your code.
I had accidentally left an v-bind:attribute empty, e.g. <el :items=""></el>. Once resolved, I was able to build/serve.
// vue.config.js
module.exports = {
chainWebpack: (config) => {
config.resolve.symlinks(false)
}
}
Link: https://cli.vuejs.org/guide/troubleshooting.html#running-installation-enter code herewith-sudo-or-as-root
In my case:
git conflicts left >>>>>> master in the component, which stopped it from compiling
I my case there was:
git conflict
a tag was not completely closed it was like <div> ..... </div but vs code was not showing this error. when I opened every component, it highlighted the error
Check all your components for merge conflicts.
If you're using vscode, try to search for the string >>>>> on your project folder.
This seems to be caused by an error in one of your project files which prevents compilation and also compresses any error message.
I was personally bothered by this today, and spent a lot of time unnecessarily debugging WSL before finding the error in one of my components.
Try to comment out or remove any components, in templates, component registrations and imports, until it starts loading again.
I ran a linter as a step before serve and noticed that it corrected one of the files. It still didn't run. But I decided to go through the file and noticed that there was one closing tag missing.
It will be tedious, but look through your components to see whether you have a missing closing tag.
I also found that checking the first place the numbers pause and using that as a way to narrow down the file with a problem helped me sort it out faster.
40% building 223/268 modules 45 active ...rders\List.vue?
In my case, one of the environment variables wasn't defined. After I defined it using Webpack DefinePlugin, it all started working again. It would be great to see an actual error in such a case instead of the build process hanging.
I solve this problem by add .eslintignore file. Because I use a big packed third-party module directly in project.
It is most likely due to an error in your source files. In my case I started by removing an import of a deleted component in the main.js, then I removed a few <style> tags from two components (vue prohibits tags that have side effects in template). It may also help to monitor the last files being processed to get a clue about where to look at.
I wasn't missing any tags, but I had copied from my data section in the script to a v-if tag (to ensure I spelled the data variable properly) and I accidentally left the : instead of changing it to an =.
If you are having this problem, it might be something else to check for. It was pretty hard to see! But by removing sections of the code a piece a a time I zeroed in on it.

Can't get webpack to load in Index.cshtml

I'm on a React project and I'm making it as an asp.Net Core-application. I'm aware of webpack to bundle files, in my case I need to get some jsx-files bundled. I have looked through some guides and tutorials on ReactJS.Net's own site and this Youtube video etc. What I have so far is my index file Index.cshtml:
#{
Layout = null;
}
<html>
<head>
<title>Hello React</title>
</head>
<body>
<div id="content"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.2/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.2/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/remarkable/1.7.1/remarkable.min.js"></script>
<script type="text/javascript" src="bundle.js" charset="utf-8"></script>
</body>
</html>
And then made a package.json through the npm init-command in node.js with all the default props except the name:
{
"name": "marck",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"babel": "babel",
"webpack": "webpack"
},
"author": "",
"license": "ISC",
"devDependencies": {
"babel-core": "^6.20.0",
"babel-loader": "^6.2.9",
"babel-preset-es2015": "^6.18.0",
"babel-preset-react": "^6.16.0",
"react": "^15.4.1",
"react-dom": "^15.4.1",
"webpack": "^1.14.0"
}
}
Created a webpack.config.js-file:
var path = require('path');
var webpack = require('webpack');
module.exports = {
entry: './app.jsx',
output: {
path: __dirname,
filename: 'bundle.js'
},
module: {
loaders: [
{
test: /.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2015', 'react']
}
}
]
},
};
And finally I have created the app.jsx-file I want to get bundled in webpack, and it's the code from the example on ReactJS.Net:
import React from 'react'
import ReactDOM from 'react-dom'
var CommentBox = React.createClass({
render: function() {
return (
<div className="commentBox">
Hello, world! I am a CommentBox.
</div>
);
}
});
ReactDOM.render(
<CommentBox />,
document.getElementById('content')
);
When I run webpack in node.js command prompt it says:
Assets Size Chunks Chunk Names
bundle.js 740 kb 0 [emitted] main
+ 179 hidden modules
So it looks like it bundles something or am I wrong?
When I try run it, it gives me this GET-error in the browser
GET http://localhost:9217/bundle.js
And this:
[15:22:51 GMT+0100 (Romance Standard Time)] Browser Link: Failed to invoke return value callback:
TypeError: Cannot read property 'files' of null
My folders are set as follows:
Solution 'webpack'
>Solution Items
>src
>webpack
>wwwroot
>Dependencies
>Controllers
>Views
>Home
Index.cshtml
app.config
app.jsx
appsettings.json
bundle.js
package.json
program.cs
>project.json
Startup.cs
web.config
webpack.config.js
I hope some of you can tell me what I need to do to get this to work, because I think that the documentation and the guides aren't that clear all the time. Everybody shows different ways to do it, and I'm kind of confused now.
EDIT:
I've found out, that the applikation only looks in the wwwroot-folder when it's an asp.Net Core applikation, so I tried to put the bundle.js-file in that folder and then changed the direction in my Index.cshtml-file to that and then it worked. I hope this will help others :)

Testing React components with Mocha: unexpected token

I have my React components all fleshed out, and I wanted to learn how to test these components properly with Mocha + chai. I have these configurations for my package.json (relevant ones):
"scripts": {
"start": "http-server",
"build": "watchify main.js -t babelify -o bundle.js",
"test": "./node_modules/mocha/bin/mocha --compilers js:babel-core/register test/test*.js"
},
"devDependencies": {
"babel": "^5.6.23",
"babelify": "^6.1.3",
"browserify": "^11.0.0",
"chai": "^3.5.0",
"jsdom": "^9.8.3",
"mocha": "^3.2.0",
"react-addons-test-utils": "^15.4.1"
},
"babel": {
"presets": [
"es2015"
]
}
I have Skill.js:
import React from 'react';
import _ from 'underscore';
export default class Skills extends React.Component {
render() {
return (
<div>
<h1>T E S T</h1>
</div>
)
}
}
along with a test.js in a folder called test:
import React from 'react';
import { expect, assert } from 'chai';
import Skills from '../src/components/Skills.js';
I'm receiving an unexpected token error when I run npm test.
What's the console complaining about? Why is the <div> tag not valid?
I had a similar issue and at first I thought I did not import React from 'react';.
Next I found out that I did not add --require ./test/test_helper.js
And last but then after still not working, it dawned on me that I did not restart node. That fixed it for me.
You need to install babel-preset-es2015 before using it
npm install --save-dev babel-preset-es2015

Resources