Node app failing during reactDOM.render() - node.js

I'm trying to run a existing React/Node application locally. It is failing on my index.js at the line where it calls reactDOM.render()
Module parse failed: C:\Users\dan\Documents\Development Projects\diy-data\client\index.js Unexpected token (30:2)
You may need an appropriate loader to handle this file type.
When I try to run the file using
yarn start
It's failing on this section of code in index.js:
reactDOM.render(
<MuiThemeProvider>
<Provider store={store}>
<div className="container">
<Header />
<Leftnav />
<Stepper />
<UploadScreen />
<TransformScreen />
<ConfirmScreen />
</div>
</Provider>
</MuiThemeProvider>,
root);
I assume I'm missing some kind of basic setup, but finding no information on this error.

You have to use either EXPORT or SET to create env variables and depends on your OS
"dev": "export PORT=3000 || SET \"PORT=3000\" && export NODE_ENV=dev || SET \"NODE_ENV=dev\" node --inspect=5858 server/index.js"

Related

Vite not running on codeBuild, keeps saying cannot import SVG

I've been trying to learn AWS's CDK and one of my attempts involved using a seperate repositories for both the infrastructure and the application itself.
My application repository is the bog standard vite#latest install. No changes.
I'm having issues where when i deploy, the build is crashing with codeBuilds log stating src/App.tsx(2,23): error TS2307: Cannot find module './assets/react.svg' or its corresponding type declarations.
I've tried adjusting the tsconfig to include an #types folder with declarations for svg but this didn't work at all. It just gave more typescript errors.
I feel like i'm missing something really silly.
My CDK Pipeline:
const pipeline = new CodePipeline(this, "CahmFrontendPipeline", {
pipelineName: "CahmFrontendPipeline",
synth: new ShellStep("Synth", {
input: CodePipelineSource.gitHub("myuser/myrepo", "master", {
authentication: cdk.SecretValue.secretsManager("MY_SECRET"),
}),
primaryOutputDirectory: "dist",
commands: [
"cd frontend",
"npm i",
"npm run build",
"npx cdk synth",
],
}),
});
This all works right till the codebuild. I've tried changing the image it's using as well but to no avail. Has anyone had this problem and might be able to point me in the right direction?
Things get confusing because paths act differently between dev and build (prod). I created a very simple example sandbox to help visual things using the Vite starter app. I would also recommend reading the Static Asset Handling. Also incredibly useful are the Vite Build Options which let you change where files are output.
Ideally, you want to use import reactSVG from './assets/react.svg' at the top of your component, then reference that src in the render using src={reactSVG). Both dev and build will be happy with that.
Or you should use an absolute path like /assets/react.svg, removing the . in front.
Besides the sandbox above, I wrote detailed notes on what's happening inline above each image to help the understanding.
import { useState } from "react";
import reactLogo from "./assets/react.svg";
import "./App.css";
function App() {
const [count, setCount] = useState(0);
return (
<div className="App">
<div>
<a href="https://vitejs.dev" target="_blank">
{/**
* In dev, /vite.svg defaults to the "/public/vite.svg"
* In build/prod, /vite.svg defaults to "/dist/vite.svg"
* Use absolute paths or imports (below) when possible.
*/}
<img
src="/vite.svg"
className="logo"
alt="Vite logo"
width="25"
height="25"
/>
</a>
<a href="https://reactjs.org" target="_blank">
{/**
* Due to import magic, this works in both dev / build (prod)
* Use imports or absolute paths when possible.
*/}
<img
src={reactLogo}
className="logo react"
alt="React logo"
width="25"
height="25"
/>
</a>
{/**
* Here is where things go wrong with the default configuration:
*
* Example --- src="./assets/react.svg" won't work by default. Why?
* In development, "./" equates to your project root, "/"
*
* In a basic Vite project, root contains "src", "public", and "dist", if you ran the `npm run build` command.
* As you can see, there is no "assets" folder in project root. It's only contained
* within "src" or the "dist" folder. This is where things get interesting:
*
* When you "build" your app, Vite appends unique strings at the end of your compiled .js
* files in order to avoid cache side-effects on new deployments in the front-end.
*
* So in the built app folder ("dist"), your assets will look something like this:
*
* /dist/assets/react-35ef61ed.svg
* /dist/assets/index-d526a0c5.css
* /dist/assets/index-07a082e1.js
*
* As you can see, there is no "/assets/react.svg". It does not exist in the build,
* which is why it's recommended that you import images at the top of your component
* for local assets. You can use remote assets as inline string paths. ("https://...")
*/}
<a href="https://vitejs.dev" target="_blank">
<img
src="./assets/react.svg"
className="logo"
alt="Never be visible"
width="25"
height="25"
style={{ border: "1px red solid" }}
/>
</a>
{/* only works in dev, non-build */}
<a href="https://vitejs.dev" target="_blank">
<img
src="/src/assets/react.svg"
className="logo"
alt="Visible in dev"
width="25"
height="25"
style={{ border: "1px solid green" }}
/>
</a>
</div>
<h1>Vite + React</h1>
<div className="card">
<button onClick={() => setCount((count) => count + 1)}>
count is {count}
</button>
<p>
Edit <code>src/App.jsx</code> and save to test HMR
</p>
</div>
<p className="read-the-docs">
Click on the Vite and React logos to learn more
</p>
</div>
);
}
export default App;
So to those who find this question i've put here, the problem was from 2 different sources for me.
First, The version of the image used for the codebuild was defaulting to version 1 every time I redeployed as i hadn't chosen a specific image to use.
Secondly, this pipeline function isn't made for what i wanted it to do. For context, if you are wanting to build a source => build => deploy framework, make sure to use aws_codePipeline.Pipeline to build out each step.
You can find good examples of this in their documentation.

SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON

This is a PERN app. I don't remember ever getting this error and I haven't found any records when doing a Google search.
I don't see anything wrong in the index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<!-- <link rel="manifest" href="%PUBLIC_URL%/manifest.json" /> -->
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>
Any idea where it comes from? I get it as soon as I start the app.
I'm just a beginner but it happens when you are passing the wrong URL to the fetch function, suppose that your db.json file is running on port 8000 and you are passing port 3000, that's why.
useFetch("http://localhost:3000/blogs/" + id);
Instead, try this, it might helps. :)
useFetch("http://localhost:8000/blogs/" + id);
Hope it helps.
So I had this same error when I installed npm gh-pages. My solution was to delete the Homepage link in package.json and it worked.
I had the same problem .
If you are using node server, install this npm install body-parser
and add these lines in your server-side code
const bodyParser = require("body-parser"); router.use(bodyParser.json());
I'm new at this, but I found if I added a proxy to my package.json (client side, not server side) it worked! It looks like this in package.json (placed above my dependencies): "proxy": "http://localhost:3001", . I believe it's because the client side can't read it, and the proxy tells it to pass it to the server side which can read it.
I got the same error while deploying the React app on Vercel. Turns out, I forgot to add environment variables to the project settings on Vercel.
Check if you are calling your api prefixing the protocol, like this 'https://apiurl...', not like this 'api.something'
Faced the same issue and it was my json path was incorrect. Initially it was fetch('./movies.json') which was incorrect path.
Fix it and now working fine:
useEffect(() => {
fetch('../movies.json')
.then(res => res.json())
.then(data => setMovies(data.posts))
}, [])
I was trying to fetch data from the backend into my react application, with out mentioning the proper path of the url in the loader function of the react-router library, hence this issue occured and once I defined the correct path, it worked just fine.
const response = await fetch("http://localhost:8080/events");
I forgot to mention "events" in the url.

how to deploy ExpressJS in TypeScript to Azure?

I am trying to create an Express Server for API service, using this express generator:
generator-express-no-stress-typescript
I can run the Express Server locally using npm run dev.
I can run npm run compile to create the production build in dist folder.
The the dist folder product package can be started using npm run start without issue.
However, I failed to deploy the app to my Azure server. I have followed this Microsoft document, to deploy the Express.js to Azure App Service using Visual Studio Code. After all steps, when I browse the app it shows You do not have permission to view this directory or page.
Any article or document I can refer to? Thanks for any help.
package.json scripts section by default created by generator-express-no-stress-typescript
"scripts": {
"start": "node dist/index.js",
"compile": "ts-node build.ts && tsc",
"dev": "nodemon server/index.ts | pino-pretty",
"dev:debug": "nodemon --exec \"node -r ts-node/register --inspect-brk\" server/index.ts | pino-pretty",
"lint": "eslint -c .eslintrc.js \"{server, test}/**/*.{js,ts,tsx}\" --quiet",
"lint:fix": "eslint -c .eslintrc.js \"{server, test}/**/*.{js,ts,tsx}\" --quiet --fix",
"test": "mocha -r ts-node/register test/**/*.ts --exit",
"test:debug": "mocha -r ts-node/register --inspect-brk test/**/*.ts --exit"
},
I finally figure out what's wrong with my package and deployment. Here I would share my findings.
Azure require iisnode/web.config to execute the app
when I review this Microsoft tutorial document again, I found in their sample project, there is a web.config file at the root folder
refer to this link: https://github.com/tjanczuk/iisnode/blob/master/src/samples/configuration/web.config
it say "This configuration file is required if iisnode is used to run node processes behind"
I copied the same file to my project, which my project is generated by this generator: generator-express-no-stress-typescript
What I did to my project:
use the generator to generate the sample Express API Server
run npm run compile to compile the product build into dist folder
copy the above web.config into root folder
modify the content, for path point to index.js, change to dist/index.js
<handlers>
<!-- Indicates that the server.js file is a node.js site to be handled by the iisnode module -->
<add name="iisnode" path="dist/index.js" verb="*" modules="iisnode"/>
</handlers>
......
<rule name="DynamicContent">
......
<action type="Rewrite" url="dist/index.js"/>
</rule>
after all, I deploy the app to Azure again, now the log file error message changed. Now it shows something like "Invalid port number, should be in range 0 - 65xxx"
fixing the listing port logic
it seems Azure port number environment is not a number, it is a pipe string:
https://www.geekwithopinions.com/2013/12/09/node-js-and-azure-is-it-a-port-or-a-pipe/
however, the generated index.ts logic, since it is TypeScript, the logic parseInt for the port, and it caused error.
// server/index.ts
......
const port = parseInt(process.env.PORT ?? '3000');
export default new Server().router(routes).listen(port);
For quick test, I just want to prove how the Express Server could work on Azure, so I don't want to fix the TypeScript logic. Instead, I directly modified the compiled js file which generated by npm run compile, the tsc generated file dist/index.js which to be executed by Azure:
// const port = parseInt((_a = process.env.PORT) !== null && _a !== void 0 ? _a : '3000');
const port = (_a = process.env.PORT) !== null && _a !== void 0 ? _a : '3000';
exports.default = new server_1.default().router(routes_1.default).listen(port);
deploy again, and it works now :)

Cant Resolve Installed Npm Module

I uninstalled the package #toast-ui/react-image-editor from the server side of my react app because I thought the dependency needed to be client side, so I go and install it client side, and reboot the app and it cannot be found.
Heres my basic folder structure
-myapp
-server.js
-package.json
-node_modules
-package-lock.json
-client
-package.json
-node_modules
-package-lock.json
-src
I receive this error: "./src/components/images/Editor.js
Module not found: Can't resolve '#toast-ui/react-image-editor' in 'C:..\client\src\components\images'"
Following that I consulted
How do I resolve "Cannot find module" error using Node.js?
Can't resolve module (not found) in React.js
Basically I have deleted and installed the individual package, deleted and installed the node_modules on the client and the server run npm cache verify, installed the package on the client only, installed the package on the client and the server, installed on the server only.
and nothing is working, which makes me think possibly its an import error with VS Code,
is there a way to see how npm is trying to import a specific package or any general thing I haven't done for react failing to import a package that's clearly there.
I got the same error. I think there is a problem with the recent version 3.14.3. I went back to 3.14.2 and it worked fine. Here is my sample App.js to get you started, based on the npm page.
import 'tui-image-editor/dist/tui-image-editor.css';
import ImageEditor from '#toast-ui/react-image-editor';
function App() {
const myTheme = {
// Theme object to extends default dark theme.
};
const MyComponent = () => (
<ImageEditor
includeUI={{
theme: myTheme,
menu: ['shape', 'filter'],
initMenu: 'filter',
uiSize: {
width: '1000px',
height: '700px',
},
menuBarPosition: 'bottom',
}}
cssMaxHeight={500}
cssMaxWidth={700}
selectionStyle={{
cornerSize: 20,
rotatingPointOffset: 70,
}}
usageStatistics={true}
/>
);
return (
<div className="App">
<header className="App-header">
<div><MyComponent /></div>
</header>
</div>
);
}
export default App;

React.js website build works on one host, but not another

I am new to react.js . I have created a react website using create-rect-app. I have run: npm run build in git and got my static site files. Everything works on the test host, however when i moved hosts only index page works and navigating to other page gives 404 error. For routing im using react-router-dom.
How can i get my page to work on the other host?
Working host: http://000webhost.com/
Badly working host is some local provider
Edit: Basically i have pages such as /Home and /Contact.
Im using react-router-dom.
code:
import React, { Component } from 'react';
import { BrowserRouter as Router, Route} from 'react-router-dom';
import logo from './logo.svg';
import './App.css';
import Home from './pages/Home.jsx';
import Contacts from './pages/Contacts.jsx';
import Our_products from './pages/Our_products.jsx';
class App extends Component {
render() {
return (
<Router>
<div>
<Route exact path ="/" component={Home}/>
<Route exact path ="/Home" component={Home}/>
<Route exact path ="/Contacts" component={Contacts}/>
<Route exact path ="/Our-products" component={Our_products}/>
</div>
</Router>
);
}
}
export default App;
My index is linked to /Home as you can see from code. i have uploaded Build folder to public_html on both hosting platforms. On one site works normaly, on the other only /Home page shows up.
So, you can ignore this, but what helped is changing
<a href="/" />
to
<Link to="/" />
. Basically one hosting provider could render links as
<a />
other only as
<Link />

Resources