Simple Node App Template

A simple web app starter in node.js express

In this web app, there is only going to have one client side html file and two server side node.js files. The html file will have to forms. One with GET method that submits a name to the server server and the server will respond with a greeting message. The other form with POST method that submits two numbers to the server and the server will respond with the sum of the two numbers.

1. Make sure you have node.js installed, it can be downloaded from http://nodejs.org/

2. Create a root folder for the this simple node.js web app with this structures.

└── my-web-app ├── node └── public mkdir my-web-app cd my-web-app mkdir node mkdir shell

3. Create the file my-web-app/node/package.json, it is for install the node modules we will need for this simple node express web app.

< "name": "my-web-app", "version": "1.0.0", "description": "A simple node js express web app", "author": "yourname ", "dependencies": < "express": "", "body-parser": "" >, "private": true >

4. With the above we can run the sudo npm install command in to install the dependency node modules express ad body-parser. It will be fine without the package.json file and install these two node modules one by one from the command line.

5. The html file, my-web-app/public/index.html

      

PLUS

6. The web app init file, my-web-app/node/server.js

var express = require('express'), bodyParser = require('body-parser'), app = express(), service = require('./service.js'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded(< extended: true >)); app.use(express.static('../public')); service.attachService(app); app.listen(3333); console.log("server at http://localhost:3333");

7. The web app service file, my-web-app/node/service.js

function greeting(req, res) < var fn = req.query.firstname; res.send("Greetings, " + fn); >function additon(req, res) < var n1 = req.body.num1, n2 = req.body.num2, sum = parseInt(n1,10) + parseInt(n2,10); res.send(n1 + ' plus ' + n2 + ' is equal to ' + sum); >var attachService = function (app) < app.get('/svc/greeting', greeting); app.post('/svc/add', additon); >; exports.attachService = attachService;
cd my-web-app/node node server.js

9. Open the browser and go to http://localhost:3333

Search within Codexpedia

Источник

My app public index html

Last updated: Apr 19, 2023
Reading time · 5 min

banner

# React: Could not find a required file. Name: index.html

The React.js error «Could not find a required file. Name: index.html» occurs for multiple reasons:

  • Renaming, deleting or moving the index.html file from your public/ directory.
  • Not having the package.json and package-lock.json files in the root directory of your project.
  • Adding the index.html file or the public directory to your .gitignore file.
  • Not opening your terminal in your project’s root directory when issuing the npm start command.
Читайте также:  Java get all loggers

could not find required file

# Make sure the index.html file is in your public/ directory

The first thing you need to verify is that you have an index.html file in your public/ directory.

In a simple Create React App project, your folder structure will look similar to the following.

Copied!
my-project/ └── public/ └── index.html └── src └── App.js └── index.js └── package.json

make sure index html file is in public directory

You might have deleted, renamed or moved your index.html file.

The public/ directory should be located at the root of your project, right next to your src/ directory.

If you can’t find your index.html file in the public/ directory, create a new public/index.html file using the following template.

Copied!
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="Website created using create-react-app" /> link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" /> link rel="manifest" href="%PUBLIC_URL%/manifest.json" /> title>React Apptitle> head> body> noscript>You need to enable JavaScript to run this app.noscript> div id="root">div> body> html>

You can also find the default Create React app index.html file in the project’s GitHub repository.

add index html to public folder

You can view the entire public/ folder of a Create React app by clicking on the following link.

Once you create the index.html file in the public/ folder and paste the content, try to restart your server with the npm start command.

# Creating a new React App project and copying the missing files

If the error persists, you can also create a new Create React App project and copy over the missing files/folders.

Open your terminal in a different directory and issue the following command to create a new project.

Copied!
# Create a new JavaScript project npx create-react-app my-app # or a TypeScript project npx create-react-app my-ts-app --template typescript

The first command generates a new Create React App JavaScript project.

If you need to generate a TypeScript project, use the second command.

Once you generate the new project, you can copy over any missing files or directories.

Your project’s folder structure should look similar to the following.

Copied!
my-project/ └── public/ └── index.html └── src └── App.js └── index.js └── package.json

# Check your Git history or status

If the issue persists or you don’t want to use the template index.html file, check if you’ve moved, renamed or deleted your index.html file.

You can use the git status command to print any changes you’ve made since the last commit.

If you’ve already committed the changes, open your repository on GitHub and click on commits

open github repo click commits

Once you open the commits page, you can click on the < >icon to browse the repository at the time of each commit.

browse repository at time of specific commit

You can view the contents of your public/ directory for a previous commit and copy over the files that are missing.

# Make sure the package.json file is present in your root folder

Another common cause of the error is deleting or renaming your package.json or package-lock.json files.

Make sure the two files are present in the root directory of your project.

Copied!
my-project/ └── public/ └── index.html └── src └── App.js └── index.js └── package.json └── package-lock.json

If your package-lock.json file is missing, you can run the npm install command to regenerate it.

Copied!
# with NPM npm install # or with YARN yarn install

However, if your package.json file is missing you have to either figure out where it went or use a boilerplate one.

Here is an example boilerplate package.json file.

Copied!
"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", "react": "^18.2.0", "react-dom": "^18.2.0", "react-scripts": "5.0.1", "web-vitals": "^2.1.4" >, "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" ] > >

You can also generate a new Create React App project and copy over the default package.json file.

Copied!
# Create a new JavaScript project npx create-react-app my-app # or a TypeScript project npx create-react-app my-ts-app --template typescript

Make sure your package.json file is located in the root directory of your project, right next to the src/ and public/ folders.

# Make sure you haven’t added index.html to .gitignore

Another common cause of the error is adding your index.html file or your entire public/ directory to your .gitignore file.

If you deploy your project to Heroku, GitHub pages or any other hosting service and your public/ folder or your index.html file is missing, the error is raised.

Your .gitignore file should be located in the root directory of your project, right next to your package.json file.

Источник

Блог

Я создаю проект веб-сайта в React, и мне нужно добавить некоторый код в public/index.html досье. в index.html файл пуст, и я не могу отредактировать его. Это нормально? Я использую VS Code в качестве редактора.

Комментарии:

1. Я использую VS Code в качестве редактора.

2. Как вы создали свой проект? Создать приложение react?

3. Я использовал Create react app

4. Если вы сделаете это за пределами папки вашего проекта npx create-react-app my-app , сгенерированный public/index.html файл не будет пустым

5. Я использовал npx create-react-app my-app для создания проекта, но public/index.html файл пуст.

Ответ №1:

Попробуйте использовать другой редактор IDE / кода, который вы используете прямо сейчас

Комментарии:

1. Этот ответ такой же расплывчатый, как и вопрос: D также не помогает

2. Я думаю, что мой вопрос очень специфичен.

Ответ №2:

Значение по умолчанию my-app/public/index.html после запуска npx create-react-app my-app должно быть

 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" />  link rel="manifest" href="%PUBLIC_URL%/manifest.json" />  title>React App title> head> body> noscript>You need to enable JavaScript to run this app. noscript> div id="root"> div>  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> 

Комментарии:

1. Я знаю, что это должно быть, но я только что создал другое npx create-react-app и воспроизвел точную проблему, с которой я изначально начал.

2. Здесь мы упускаем какой-то важный шаг, чего-то не хватает. Я буквально только выполнил стандартную команду, о которой уже упоминалось, и это было результатом public/index.html , поэтому мне понадобится что-то еще. Какие шаги необходимы для воспроизведения?

3. Я согласен; чего-то не хватает. Возможно, сбой с vscode. Может быть, мне следует удалить; это странно.

4. Что вы видите в своем терминале после запуска этого в пустой папке npx create-react-app my-app amp;amp; cat my-app/public/index.html ?

5. если вы видите содержимое из index.html значит, что-то не так с редактором, которого я предлагаю

Источник

Оцените статью