Tag Archives: js

AccessBlank Page: js File Error: failed(ERR_CONTENT_LENGTH_MISMATCH)

problem

Today, when I open my personal homepage http://cdfive.com to find that it is blank, I can display it after F5 refresh several times.
In chrome Ctrl+Shift+N open a new window to visit again, the page shows blank, after many times F5 refresh still blank.
F12 open the console, in Network, I see that the jquery.js that get the home page inside the error, status is FAILED, click FAILED to expand the error message as net::ERR_CONTENT_LENGTH_MISMATCH.
In the Console also see the error, jquery.js failed to get the home page js error.

net::ERR_CONTENT_LENGTH_MISMATCH 200
(index):13 Uncaught ReferenceError: $ is not defined
    at (index):13

Analysis:
Check the Nginx log
cd /usr/local/nginx/
tail -fn 50 error.log

2022/01/15 16:01:29 [crit] 4775#0: *703880 writev() "/usr/local/nginx/proxy_temp/7/24/0000042247" failed (28: No space left on device) while reading upstream, client: x.x.x.x, server: xxx.com, request: "GET /.../jquery.1.10.2.js HTTP/1.1"
, upstream: ...

Through DF - H , it is found that the disk space is 100%

Solution:

Starting from the/root directory, use the command:

du -sh *

du -h --max-depth=1

Find directories that take up more space

It is found that there are too many sentinel log files in the /root/logs/CSP directory

cd /root/logs/csp

ll | wc -l

There are 5351 log files.

rm -rf *.2021*

ll | wc -l

Delete the log files in 2021, and 241 files remain, freeing up 15g of space

Then DF -H, 61% disk space

Visit the home page again, the page display is OK, and the nginx log is normal.

Solve the problem of JS using JSX syntax to report errors in vite react project

background

During the vite test of stock items, it is found that many stock (old) items directly write JSX syntax in JS, and a lot of problems will be thrown when vite is used to start failed to parse source .

It’s not too much trouble to run a script to modify the file type in batch. This is a solution.

In order to get to the bottom of the matter and access vite for the lowest cost of stock projects, try to avoid modifying the business code. We have to find another way to solve it.

The screenshot of error reporting is as follows

Recurrence problem

Initialize demo project

# npm 6.x
npm init vite@latest my-react-app --template react-ts

# npm 7+, extra double-dash is needed:
npm init vite@latest my-react-app -- --template react-ts

# yarn
yarn create vite my-react-app --template react-ts

The contents are as follows

├── index.html
├── package.json
├── src
|  ├── App.css
|  ├── App.tsx
|  ├── favicon.svg
|  ├── index.css
|  ├── logo.svg
|  ├── main.tsx
|  └── vite-env.d.ts
├── tsconfig.json
└── vite.config.ts

start-up

npm run dev

The page is normal. Next, modify app. TSX to app. JS

You will get the above error report

reason

    Vite will do the dependent pre build at startup

    pre built , runtime only performs syntax conversion between JSX and TSX by default. Will not do JSX syntax conversion for JS.

Solution

    Modify the configuration that depends on the pre build

    Use the Babel plug-in @ Babel/plugin transform react JSX , and let vite convert JS files at runtime

Add a little configuration to the configuration file as described in the document

export default defineConfig({
  build:{
    rollupOptions:{
      input:[]
    }
  },
  optimizeDeps: {
    entries: [],
  },
})

By reading the documentation of @ vite/plugin react , we found that it supports incoming Babel plug-ins

npm i @babel/plugin-transform-react-jsx

Add plug-in

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react({
      babel: {
        plugins: ['@babel/plugin-transform-react-jsx'],
      },
  })],
})

Start the verification again and an error is found

The reason is that react is not introduced into app.js. Let’s introduce it

import React,{ useState } from 'react'

be accomplished

summary

Two treatment schemes

    File suffix JS = & gt; jsx

    Modify the dependency pre build configuration and add Babel plug-in @ Babel/plugin transform react JSX

The second method will affect the startup speed of the project to a certain extent. Readers can pick the scheme according to the actual project situation

last

Welcome to share/exchange some problems and lessons learned when accessing vite in the development process in the comment area

Source address

JS declares two variables with the same variable name

When writing, you should probably not write the same variable name, that is, the local variable and the global variable may have the same name

However, when both are variables in the same region, such as all global variables

other languages probably report errors, but JS is too tolerant. It’s a little difficult to report errors

        var t={
            u:"syyys"
        }
        var t="ss";

Now the second is equivalent to

t="ss";

How does eclipse ignore JS files with errors

The first step is to locate the error, select window – show view – other in the menu, and select problems

 

Step 2: click the item with Red Cross. In the problems view, you can see what the error is and the JS error in which folder

 

Step 3: after locating the error, right-click the item with the Red Cross, select properties, and the Properties box pops up

Step 4: in the pop-up menu, select include path under JavaScript directory, select excluded under source on the right, and then click Add Folder

 

Step 5: in the pop-up box, under exclusion patterns, click the Add button on the right to add the path to be ignored

 

Step 6: click add, select browse in the pop-up box, and select the file to be ignored under the project

 

 

 

Step 6: click OK and return to the project directory. You will see that the projects that reported the red cross just now have returned to normal

Welcome to my personal blog – Fu Bohan’s personal blog   vast waves

 

Error in JS function referencing public page [How to Solve]

For the website, there are a large number of sharing modules between many pages, such as page header, footer and user bar. Many times, in order to be convenient and easy, we write functions in public modules and call them in other pages. However, when we reference public JS functions, some can be referenced, but some report errors this is because of the problem of JS loading, that is, when the current page is loaded, but some public pages reference public JS before loading, it will report that this function is not found


JS

The results are as follows:

JS referencing public footer

The results are as follows:

from the above two examples, we can know that the loading order of JS is from top to bottom. The header is loaded first – the current page – the footer. Finally, if all the current pages reference the footer that has not been loaded, JS will report “F”_public is not defined”

 

The solution is as follows:

$(document).ready(function () {
        f_public();
})

when the DOM (document object model) has been loaded and the page (including image) has been completely rendered, the ready event will occur; This function is not called until the footer is loaded

page execution sequence in JS

1: Use $(function) {} of jQuery

2: Use $(document). Ready (function() {}) of jQuery; There is no essential difference between the first two. The first is the abbreviation of the second. The second is to execute the method after the document is loaded

3: Use $(window). Load (function() {}) of jQuery

4: Use window. Onload = function() {} the third and fourth methods wait until the whole window is loaded to execute the method body. There is no difference between the two, except that one uses DOM objects and the other uses jQuery objects

5: Statically bind the onload event on the tag, & lt; body onload=”aaa()”> When the body is loaded, the AAA () method is executed

 

So, what is the implementation order of these five methods

Through the following code verification, it is found that:

Use $(function) {} of 1: jQuery and $(document). Ready (function() {}) of 2: jQuery; No matter where the position is placed, the other three methods always take precedence (the reason is that these two methods are executed after the document is loaded, and the last three methods are executed after the whole window page is loaded). The execution order between the two is who is at the top and who takes precedence

Use $(window). Load (function() {}) of 3: jQuery

4: window. Onload = function bbb() {} always takes precedence over & lt; body onload=”aaa()”> Execution. Their execution order is also based on who is at the top and who is first

Use 5: & lt; body onload=”aaa()”> Always last

<script type='text/javascript'>

  window.onload = function(){
    alert("Page loading completed====》onload");
  }

  $(window).load(function(){
    alert("jquery===》window load" );
  })

  $(document).ready(function () {
    alert("jquery====》document ready");
  });

  $(function(){
    alert("jquery====》document onload");
  });

  function aaa(){
    alert("Static labels====》onload");
  }

</script>

<body onload="aaa()">

</body>

 

On the error of cannot read property ‘xxx’ of null in JS

Cannotreadproperty'firstChild'ofnull

When debugging the page, there was such an error. The search found that this error occurred before the page was loaded when JS was loaded. The solution is very simple. Put this section of JS at the bottom of the page, and then load this section of JS when the page is loaded. Make a brief note

Success comes from diligence

[How to Solve] Cannot set property ‘onclick’ of null

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
        <script>
            //Get this element from the document based on the value of the id attribute
            var btnObj=document.getElementById("btn");
            // for the current button element (object), register the click event, add the event handler (anonymous function)
            btnObj.onclick=function(){
                //response to do something
                alert("jaja");
            };
        </script>
    </head>
    <body>
        <input type="button" value="Display effect" id="btn" />    
    </body>
</html>

After the above code is executed, the

To make changes, you need to put the JS file at the bottom of and load it

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>    
    </head>
    <body>
        <input type="button" value="show effect" id="btn" />    
        <script>
            //get this element from the document based on the value of the id attribute
            var btnObj=document.getElementById("btn");
            // for the current button element (object), register the click event, add the event handler (anonymous function)
            btnObj.onclick=function(){
                //response to do something
                alert("jaja");
            };
        </script>
    </body>
</html>

The code executes normally

Reason: when the JS file is placed in the head, if the onclick or OnMouseOver event is bound, a similar error will appear as shown in the figure above. The reason is that the order of loading the HTML document you write is from top to bottom, and the JS is executed only after the button node is loaded. Therefore, when the browser parses from top to bottom, the button node bound to onclick cannot be found, so an error is reported

The solution: first, load the JS file at the bottom; Second, use window. Onload = function () {} to wrap JS content

Js Error: SyntaxError: identifier starts immediately after numeric literal

SyntaxError: identifier starts immediately after numeric literal

Today I wrote a onclick() method, there is such a variable 4028b88161c881ff0161c88b80dc0002

I need to pass the value of this variable into the method, but it never works:

I found that directly var aa =4028b88161c881ff0161c88b80dc0002 ;js is holding the error

The solution is as follows:

 

$(function(){
var str = “509edbe9-2914-431f-9128-97d368b7da0b”;

//The wrong way to write it
var html = ‘<button class=”button” id=”ensure” onclick=”test(str)”>OK</button>’;// Passing a string as an argument to a function reports an error directly

//The correct way to write it

var html = ‘<button class=”button” id=”ensure” onclick=”test(\”+str+’\’)”>OK</button>’;//execute correctly, note that the first \ is followed by two single quotes

$(“#dd”).append(html);

});
function test(id){
console.log(id);
}
<div id=”dd”></div>

ToFixed, toexponential, toprecision in JS

ToFixed (): converts a number to a string according to the specified number of digits after the decimal point. It does not use exponential counting

Toexponential(): converts a number to an exponential string according to the number of digits specified after the decimal point. There is only one digit before the decimal point, and the number of digits after the decimal point is specified by parameters

Toprecision(): converts a number to a string based on the number of significant digits. If the number of significant digits is less than the integer part of the number, it is expressed as an exponential string

The above three methods all follow the principle of “rounding off” or filling 0

Here are some examples:

var num = 1234567.8999;
console.log("num.toFixed(0):" + num.toFixed(0));
console.log("num.toFixed(2)" + num.toFixed(2));
console.log("num.toFixed(5)" + num.toFixed(5));
console.log("num.toFixed(12)" + num.toFixed(12));

console.log("num.toExponential(3):" + num.toExponential(3));
console.log("num.toExponential(0):" + num.toExponential(0));

console.log("num.toPrecision(1):" + num.toPrecision(1));
console.log("num.toPrecision(5)" + num.toPrecision(5));
console.log("num.toPrecision(12)" + num.toPrecision(12));

Corresponding to the following output: