Category Archives: JavaScript

@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 ' ) {
      
            }

[Go] Can structure/structure pointer be compared with operator == is not defined error

Can two instances of the same struct be compared == !=
Answer: yes or no

Can two different instances of struct be compared == !=
Answer: yes or no

If all the member variables of the structure are comparable, then the structure can be compared.
If there are incomparable member variables in the structure, then the structure cannot be compared

    type s2 struct {
        name string
    }
    aa: = s2{
        name: " aa " ,
    }
    bb: = s2{
        name: " aa " ,
    }
    fmt.Printf( " %v\n " , aa == bb)

This returns true

If it is a structure pointer, return false

 

When there are incomparable fields, an error will be reported at compile time

 

 Change to a structure pointer, there will be no error

 

 Return result false; true

Code:

    type s1 struct {
        one map[ string ] string 
        two [] string 
        three string
    }

    a: = & s1{
        one: map[ string ] string { " aaa " : " bbb " },
        two: [] string { " aaa " , " bbb " },
        three: " aaaa " ,
    }
    b: = & s1{
        one: map[ string ] string { " aaa " : " bbb " },
        two: [] string { " aaa " , " bbb " },
        three: " aaaa " ,
    }
    c : = a
    fmt.Printf( " %v;%v " , a == b, a == c)

[Go]Understand the golang project performance analysis tool PProf

PProf uses profile.proto to analyze data

Can collect command analysis when the program is executed

Run-time data analysis during HTTP service can be collected

Can be analyzed by go test test case

 

There are the following monitoring and analysis functions:

CPU analysis, memory analysis, blocking analysis, mutex analysis, Groutine analysis

 

If it is an http service, then it can be achieved by directly importing this package _ “net/http/pprof”

If you use the gin framework, you need to import this package github.com/gin-contrib/pprof

And register the gin object pprof.Register(g)

 

Directly visit http://service/debug/pprof/ through the browser

You can see the following page

 

 

 The meaning of each parameter is:

allocs: view all past memory allocation sample
blocks: view the stack trace that caused blocking synchronization
cmdline: the complete call path of the command line of the current program
goroutine: view all currently running goroutines stack trace
heap: view the memory allocation of active objects
mutex: View the stack trace
profile of the competing holder that caused the mutex lock : CPU Profiling is performed for 30s by default, and a profile file for analysis is obtained.
threadcreate: View the stack trace of creating a new OS thread

 

Use the interactive command line to analyze the results of the above URL

For example, analyze the resident memory situation

go tool pprof -inuse_space http://localhost:8081/debug/pprof/heap input top command

 

 

 

For example, analyze the temporary allocation of memory

go tool pprof -alloc_objects http://localhost:8081/debug/pprof/heap input top command

 

 

 

Analyze goroutine

 go tool pprof http://localhost:6060/debug/pprof/goroutine You can use traces to see the call stack

The focus is on the independent goroutine that I opened myself, and the bottom one is the call function of the package I wrote.

[Go]Understand the golang project performance analysis tool trace

When using PProf is not too detailed, you can use trace to view the trace.

This command can be used with PProf

Download the trace file first

curl http://domain name/debug/pprof/trace?seconds=20> trace.out 

 

use

go tool trace C:\Users\shihan1\Downloads\trace.out

Because it is monitoring 127.0.0.1, it may be inconvenient to access on the server line

 

 

 

To use this tool, you need to install graphviz first

Windows system can go here to download, pay attention to check and add environment variables during installation, otherwise you need to manually add

http://www.graphviz.org/download/#windows

You can see the analysis by visiting the address