Category Archives: JavaScript

Vue displays 404 and 500 interfaces according to HTTP response status

Requirement: when responding to an error, the rendering will display the interface with error information
preparation: create error information interfaces 400. Vue and 500. Vue in content
note: pay attention to the level of routing where the error interface needs to be placed (I’m under children)

1、 Create route (routes/index. JS)

	export default {
    mode: 'history',
    routes: [
        // Dynamic path parameters Start with a colon
        {
            name:'index',
            path: '/',
            component: () => import('@/components/QBLayout/index.vue'),
            children: [
            	{
	                name:'index',
	                path: '/',
	                component: () => import('@/components/Index/index.vue'),
           	 	},
            	{
                    name: 'error_403',
                    path: '403',
                    component:()=>import('@/components/errorStatus/403.vue')
                },
                {
                    name: 'error_500',
                    path: '500',
                    component:()=>import('@/components/errorStatus/500.vue')
                },
                {
                    name: 'error_404',//Note that this 404 route should be placed at the end
                    path: '*',
                    component:()=>import('@/components/errorStatus/404.vue')
                }
            ]
        }
    ]
}

	

2、 Response interception (util/HTTP. JS)

import Axios from 'axios'

//1.Wrapping method: for exception response codes are handled separately
const codeErrorHandle = (resData)=>{
    switch (resData.code) {
        case 404:
            router.push({
                name:'error_404'
              })
            break;
        case 500:
            router.push({
                name:'error_500'
              })
            break;
        default:
}
//2, axios interception
const instance = Axios.create({ timeout: 25000 });

//3, response interception: mainly for response processing as follows
instance.interceptors.response.use(
    res => {
        if (res.status && +res.status < 300 && res.data && +res.data.code === 1) 
            return Promise.resolve(res.data.data);
        } else {//Call codeErrorHandle to handle exception response codes
            codeErrorHandle(res.data);
            return Promise.reject(res);
        }
    },
    error => {//This is other response state judgement, not this topic, so omit it here for now}
);

Effect interface

http://localhost : 8080/test. (enter the interface not in the route, for example: test, and then press enter to display the 404 interface)

The page console error [Vue warn]: Invalid prop: custom validator check failed for prop “status“

Invalid prop: custom validator check failed for prop “status” encountered during project debugging##

First of all, I was confused. I went to the prop and didn’t have status. I really couldn’t figure out what was going on. Through the global search of status, I realized that it was the problem of style components. Because of the company’s confidentiality, I really wanted to simulate the code

<el-progress  :percentage="stepPercentage(item.step)"  status="error"></el-progress>

The status in this code is the key to error reporting. The reason is that I added an unknown attribute error of status, which makes it unrecognizable

be careful

1. The value of status can only be one of “success/exception/warning”. Other values will give the above warning. If you have to judge according to the conditions and need to give the default color, you can assign null [null, no quotation marks] to the value

<el-progress  :percentage="stepPercentage(item.step)" :status="item.step == 4 ?'success' :null"></el-progress>

2. You can’t have spaces in the parameters following status. You need to correct the format

Vue solves the problem of repeated click navigation route error

// Solve the error reported by repeatedly clicking the navigation route
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}
Vue.use(VueRouter)

Copy directly to router.js. When pasting, pay attention to the execution sequence. This section is placed in front of new vuerouter

@requestbody: How to Use or Not Use

First of all, note that @ requestbody accepts the JSON string
so write this

dataType:"json",
contentType: 'application/json',
data: JSON.stringify(data.field),

Instead of @ requestbody, you can directly receive the JSON type

dataType:"json",
data: data.field,

The situation of not using @ requestbody
front end page

$.ajax({
		url: "http://localhost:8081/role//saveOrUpdate",
		method:"post",
	   dataType:"json",     
			// contentType: 'application/json',
		data: data.field,   
		success(data){
			console.log("======================")
				console.log(data.field)
			if(data.code == 200){
			layer.msg('add success', function () {
			 window.location = 'list.html';
				}); 
				}
		},
error(data){
	console.log(data)
	if(data.code != 200){
layer.msg(data); 
								}
								}
							});

Back end:

@PostMapping("/saveOrUpdate")
    public Result saveOrUpdate(Roles roles){
        System.out.println(roles);
        boolean saveOrUpdate = roleService.saveOrUpdate(roles);
        if(saveOrUpdate == true)
            return Result.succ(null);
        else
            return Result.fail("failed to add");
    }

Using @ requestbody
front end:

$.ajax({
								url: "http://localhost:8081/role//saveOrUpdate",
								method:"post",
								dataType:"json",
								contentType: 'application/json',   
								data: JSON.stringify(data.field),  
								success(data){
									console.log("======================")
									console.log(data.field)
									if(data.code == 200){
										layer.msg('add success', function () {
										    window.location = 'list.html';
										}); 
									}
								},
								error(data){
									console.log(data)
									if(data.code != 200){
										layer.msg(data); 
								}
								}
							});

back-end

@PostMapping("/saveOrUpdate")
    public Result saveOrUpdate(@RequestBody Roles roles){
        System.out.println(roles);
        boolean saveOrUpdate = roleService.saveOrUpdate(roles);
        if(saveOrUpdate == true)
            return Result.succ(null);
        else
            return Result.fail("failed to add");
    }

‘webpack dev server’ is not an internal or external command, nor is it a runnable program or batch file. Solution: error in cnpm run dev:

‘webpack dev server’ is not an internal or external command, nor is it a runnable program or batch file. Solution
error report when executing cnpm run dev:

resolvent:

Now to use webpack you have to install both the package webpack-cli to be able to invoke the commands webpack and webpack-dev-server.
cnpm install webpack webpack-dev-server webpack-cli --save-dev

Solving routing errors by rewriting Vue push method

/**
Rewrite the push method of the route
Solve the problem of reporting an error when jumping on the same route
Add, when same route jump, trigger watch (string only, like “view?id=5″)
*/
const routerPush = Router.prototype.push
Router.prototype.push = function push(location) {
if(typeof(location)==”string”){
var Separator = “&”;
if(location.indexOf(‘?’)==-1) { Separator=’?’; }
location = location + Separator + “random=” + Math.random();
}
return routerPush.call(this, location).catch(error=> error)
}

React native android: How to Upload Formdata

  let resizedImage = file // file
  let formData = new FormData();
  let name = `xxxx.jpeg`;
  let file = { uri: "file:///" + resizedImage.path.split("file:/").join(""), type: 'image/png', name: escape(resizedImage.name), fileType: 'image/\*' };   //The key here (uri and type and name) cannot be changed,
  formData.append("file", file); //the files here are the key needed by the backend
  formData.append("token", token); //the files here are the key needed by the backend
  formData.append("key", Math.random()+'__'+name); //the files here are the keys needed by the backend
                       

How to Solve JS error: Unexpected end of JSON input,Unexpected token u in JSON at position 0

js error Unexpected end of JSON input, Unexpected token u in JSON at position 0

JSON is usually used to exchange data with the server.

When receiving server data, it is generally a character string.

We can use the JSON.parse() method to convert the data into JavaScript objects.

Try the returned results of these kinds of parameters in the Console debugging platform of Google Chrome:

JSON.parse( null );
 // null 

JSON.parse( "" );
 // VM6600:1 Uncaught SyntaxError: Unexpected end of JSON input

JSON.parse(undefined);
// VM6635:1 Uncaught SyntaxError: Unexpected token u in JSON at position 0

It can be found that the parameters of JSON.parse() must conform to the format of the JSON string to be correctly converted into objects, otherwise it may cause errors and affect other codes.

When we are not sure about the type of data returned by the server, these few examples can be used:

// Judging whether the data exists 
var str = str && JSON.parse(str) || {};

// Judging the data type 
var str = typeof str == "string"? JSON.parse(str): {};

// Catch exceptions by try catch to prevent the code from reporting errors 
var c = null ;
 try {
    c = JSON.parse(str)
} catch (d) {}

The same is true for JSON.stringify

var g = "" ;
 try {
    g = JSON.stringify(a)
} catch (u) {}

"object" == typeof a? JSON.stringify(a): a

How to Solve Bat Script Error: system error 85 has occurred

A problem,
This error is thrown when using the BAT script to copy files from a remote server

System error 85 has occurred
The local device name is already in use

My script USES disk mapping, something like this

:: Delete the last set mapping
net use Y /delete /y
:: Disk mapping
net use Y: \\ServerName\shares \\ServerName\shares /user:password /persistent:yes

Without further explanation, Google System Error 85 with “NET USE” command for the simple reason that the remote server’s protection mechanism is involved

2. Solutions
There are two solutions, one is to modify the registry of the remote server, and the other is to operate directly locally
1. Modify remote server registry
Change the value of this path in the registry from 1 to 0

HKLM\System\CurrentControlSet\Control\SessionManager\ProtectionMode

For the terminal Server of Window Server 2003, the situation is quite special. Refer to the problem of 935642
2. Modify the native script
In fact, it’s easier to just delete all the disk mappings on your machine, rather than just deleting the definition, and click on the reference method

:: Delete all set disk mappings
net use * /delete /y

Golang: How to determine structure whether it is empty

Preface

Using any programming language will encounter the problem of nullification, so how does Golang determine the nullability of a custom structure type?

In fact, the empty structure is not a simple comparison with nil. Please look at the following two methods:

package main

import (
	"fmt"
	"reflect"
)

type A struct {
	name string
	age  int
}

func (a A) IsEmpty() bool {
	return reflect.DeepEqual(a, A{})
}

func main() {
	var a A

	if a == (A{}) { // Brackets cannot be removed
		fmt.Println("a == A{} empty")
	}

	if a.IsEmpty() {
		fmt.Println("reflect deep is empty")
	}
}

Vue2.0: How to Use vue3 api to encapsulate Axios

The biggest difference between vue2 and vue3 is that vue2 uses the options API to compare with the composition API of vue3: aggregate code & amp; Logic reuse

How to use vue3 API to encapsulate Axios in vue2.0:
code directly:
1, create API folder in SRC, and create corresponding file

2, encapsulate some methods in Axios, such as get, post…

// http/axios.js
import instance from "./index"
/**
 * @param {String} method  Methods requested: get, post, delete, put
 * @param {String} url The url of the request:
 * @param {Object} data The parameter of the request.
 * @param {Object} config The configuration of the request.
 * @returns {Promise} returns a promise object, which is actually equivalent to the return value of the axios request data
 */

const axios = ({
    method,
    url,
    data,
    config
}) => {
    method = method.toLowerCase();
    if (method == 'post') {
        return instance.post(url, data, {...config})
    } else if (method == 'get') {
        return instance.get(url, {
            params: data,
            ...config
        })
    } else if (method == 'delete') {
        return instance.delete(url, {
            params: data,
            ...config
        }, )
    } else if (method == 'put') {
        return instance.put(url, data,{...config})
    } else {
        console.error('未知的method' + method)
        return false
    }
}
export default axios

3. Encapsulate some Axios request interception and response interception in the index
here, I basically don’t do any interception, I can add them if I need

// http/index.js
import axios from 'axios'

//Create an instance of axios 
var instance = axios.create({
  baseURL: "http://192.168.0.7:8366", //interface unified domain name
  timeout: 6000, //set timeout
  headers: {
    'Content-Type': 'application/json;charset=UTF-8;',
  }
})
let loading;
//Number of requests being made
let requestCount = 0
//Show loading
const showLoading = () => {
  if (requestCount === 0 && !loading) {
  
  }
  requestCount++;
}
//hidden loading
const hideLoading = () => {
  requestCount--
  if (requestCount == 0) {
  
  }
}

//Request Interceptors 
instance.interceptors.request.use((config) => {
  showLoading()
  // Determine if a token exists before each request is sent, and if it does, add the token to the header of each http request, so you don't have to add it manually for each request
  const token = window.localStorage.getItem('token');
  token && (config.headers.Authorization = token)
  //If the request method is post, the data parameter is converted to a JSON string
  if (config.method === 'POST') {
    config.data = JSON.stringify(config.data);
  }
  return config;
}, (error) =>
  // What to do with request errors
  Promise.reject(error)).

//response interceptor
instance.interceptors.response.use(( response) => {
  hideLoading()
  //response success
  console.log('Interceptor reported an error').
  return response.data;
}, (error) => {
  console.log(error)
  //Response error
  if (error.response && error.response.status) {
    const status = error.response.status
    switch (status) {
      case 400:
        message = 'Request Error';
        break;
      case 401:
        message = 'Request Error';
        break;
      case 404:
        message = 'Error requesting address';
        break;
      case 408:
        message = 'Request timed out';
        break;
      case 500:
        message = 'Internal server error!' ;
        break;
      case 501:
        message = 'Service not implemented!' ;
        break;
      case 502:
        message = 'Gateway error!' ;
        break;
      case 503:
        message = 'Service unavailable!' ;
        break;
      case 504:
        message = 'Gateway timeout!' ;
        break;
      case 505:
        message = 'HTTP version is not supported';
        break;
      default:
        message = 'Request failed'
    }
    ElMessage.error(message);
    return Promise.reject(error);
  }
  return Promise.reject(error);
});


export default instance;

4. Finally, import these files into the NAV file

import axios from "../api/axios"
//Example request
//get
//If you need to wear parameters, you can still use the template string splice `/api/v1/0?id=${id}` and write the id in parentheses
export const mokePostD = (id) => {
    return axios({
        url: '/api/v1/0',
        method: "post",
       	data,
        config: {
            headers: {
                // 'Request-Type': 'wechat'
            },
            timeout: 10000
        }
    })
}
//post
export const mokePost = () => {
    return axios({
        url: '/api/v1/0',
        method: "post",
		data,
        config: {
            headers: {
                // 'Request-Type': 'wechat'
            },
            timeout: 10000
        }
    })
}

5. Page


import { mokePost, mokePostD } from "../../api/nav";
import { ref, onMounted } from "@vue/composition-api";

export default{
	setup(props, { root }){

onMounted(() => {
      mokePost().then((res) => {
        console.log(res);
      
      });

}
	}


}

Javascript SecurityError: Failed to read the’localStorage’ property from’Window’: Access is denied for this document.

When using chrome incognito mode, third-party cookies are blocked by default 

If local storage or cookie is used, an error will be reported in js

Error SecurityError: Failed to read the ‘localStorage ‘ property from ‘Window’: Access is denied for this document.

Failed to read the the’localStorage’ property from windows: Access is denied for this document.

 

This problem can only be handled at the code level to be compatible, and no errors will be reported first.

            if (navigator.cookieEnabled&& typeof window.localStorage !== ' undefined ' ) {
      
            }