Tag Archives: json

CRA 5.0.0 Add Proxy Project Start Error [How to Solve]

Problem Description:
https://github.com/facebook/create-react-app/issues/11762#issue-1080972271
i.e.
Set the proxy in package.json, and then start the project through npm start or yarn start, the error is as follows:

>yarn start
yarn run v1.22.10
$ react-scripts start
Attempting to bind to HOST environment variable: test.localhost
If this was unintentional, check that you haven't mistakenly set it in your shell.
Learn more here: https://cra.link/advanced-config

Invalid options object. Dev Server has been initialized using an options object that does not match the API schema.
 - options.allowedHosts[0] should be a non-empty string.
error Command failed with exit code 1.

Solution: Don’t set the proxy in package.json, but set it in src/setupProxy.js, and delete the proxy in package.json, and finally restart npm start.

[Solved] JSON parse error: Cannot construct instance of

JSON parse error: Cannot construct instance of `com.request.ApplyRequest$Detail` (although at least one Creator exists): can only instantiate non-static inner class by using default, no-argument constructor; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `com.request.ApplyRequest$Detail` (although at least one Creator exists): can only instantiate non-static inner class by using default, no-argument constructor\n at [Source: (PushbackInputStream); line: 8, column: 13] (through reference chain: com.request.ApplyRequest[\"detailList\"]->java.util.ArrayList[0])

 

The problem appears: can only instantiate non-static inner class by using default
When you declare an inner class as an attribute of the current class, you need to make the inner class static, otherwise it won’t be loaded during class loading!
Solution: Declare the inner class as static directly!

[Solved] Warning: To load an ES module, set “type“: “module“ in the package.json or use the .mjs extension

In the process of learning ES6, an error is reported when and running JavaScript files, which is reproduced in detail

1. Create a new file, add test es, and use idea to open the folder
2. Add package.json file: NPM init – y
3. Create a new test.js file in the folder test-es, the contents of which are as follows

let a = 1111
let b = 2222
var c = function(){
	console.log(3333)
}
function ddd(){
	console.log(4444)
}
function eeeeee5(){
	console.log(555)
}
export {
	a,
	b,
 	c,
    ddd,
	eeeeee5 as eee, //The way to rename: name eeeeeeee as eee, you can output the same variable or method with different names
	eeeeee5 as e5 // rename the way: name eeeeee as eee, you can output the same variable or method with a different name
}

4. Right click and click Run ‘test.JS’, the error is reported as follows:

Solution:

According to the error message, in package JSON add “type”: “module”, and then run test.JS file, no error will be reported

[Solved] PHP post Datas json_decode Error: 4 JSON_ERROR_SYNTAX

Error description

In the PHP development process, when processing json strings, json_decode returns NULL, calling last_error returns 4 (JSON_ERROR_SYNTAX), but json strings can be correctly processed by other languages ​​such as python, javascript or some online json parsers.

Diagnosis

There are several situations that generally cause php json_decode errors here:

1. The json string is read from a file and the character order mark (BOM) is not removed

2. json contains invisible characters, json_decode parsing errors

3. json object value is a single-quoted string

In particular, the third error is relatively hidden, the naked eye is often easy to ignore

Solution:

The following solutions are given for the above three cases

1.BOM Issue:

Open the file in binary mode and confirm whether there is a BOM. If so, remove the BOM before parsing. The following code takes UTF-8 as an example to detect and delete BOM.

function removeBOM($data) {

if (0 === strpos(bin2hex($data), ‘efbbbf’)) {

return substr($data, 3);

}

return $data;

}

2.Invisible character

Remove invisible characters before parsing.

for ($i = 0; $i <= 31; ++$i) {

$s = str_ replace(chr($i), “”, $s);

}

3.Single quote string value

Let’s look at the following example:

<?php

$s = “{\”x\”:’abcde’}”;

$j = json_ decode($s, true);

var_ dump($j);

echo json_ last_ error() . “\n”;

PHP 5.5. 9 output

NULL

four

Generally, you only need to replace single quotation marks with double quotation marks. During specific processing, you should pay attention to that single quotation marks may also appear in other places. Whether to replace them globally needs to be analyzed according to the specific situation.

IE8 browser Webloader will always go uploaderror and report error: http

When using Baidu webloader, the IE8 browser will always use the uploaderror when debugging

uploader.on( 'uploadError', function( file,reason ) {
     alert(reason) ;
});

The reason error is http. The reason is:
the reason why JSON is returned when it is returned in the background.

The backend of webuploader cannot return json, convert json to string type, take com.alibaba.fastjson.JSONObject as an example,
com.alibaba.fastjson.JSONObject.toJSONString([json or object data]);

[Solved] Error while extracting response for type [] and content type []…

When resttemplate is used to request restful interface, the returned JSON data will always be parsed into XML data for processing under specific circumstances, and then the error in the title will appear:

Error while extracting response for type [] and content type [application/xml;charset=UTF-8]; nested exception is org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Unexpected character ‘5’ (code 53) in content after ‘<‘ (malformed start element?).
at [row,col {unknown-source}]: [1,15395]; nested exception is com. fasterxml. jackson. databind. JsonMappingException: Unexpected character ‘5’ (code 53) in content after ‘<‘ (malformed start element?).

According to the error information, it seems that the response header marks the return type as [application/XML; charset = UTF-8], but the actual situation is that all the returned data is [application/JSON; charset = UTF-8].

After tracing the resttemplate source code, it is found that the instance created by new resttemplate (httprequestfactory()) will have 7 Converters:

Continue to track the exchange of the resttemplate. When performing type conversion on the response, all converters in the current instance will be iterated, and then select a converter that supports the current type for execution. Use canread to judge:

At this time, the problem is found. Under certain circumstances, the contenttype of the response header is read as “application/XML”. However, the real data at this time is still in JSON format. Therefore, if the converter for XML format is deleted, the iterator will look for the next executable converter, mappingjackson2httpmessageconverter. Or change the order of the two to reduce the priority of XML.

Solution:

1: Delete XML converter

    @Bean
    public RestTemplate restTemplate() {
        RestTemplate template = new RestTemplate(httpRequestFactory());
        // Exclude xml parsing converters to avoid parsing json data as xml
        List<HttpMessageConverter<?>> collect = template.getMessageConverters().stream().filter(m -> !(m instanceof MappingJackson2XmlHttpMessageConverter)).collect(Collectors.toList());
        template.setMessageConverters(collect);
        return template;
    }

2: Reduce XML converter priority

    @Bean
    public RestTemplate restTemplate() {
        RestTemplate template = new RestTemplate(httpRequestFactory());
        // Turn down the priority of xml parsing
        int xml = 0, json = 0;
        List<HttpMessageConverter<?>> messageConverters = template.getMessageConverters();
        for (int i = 0; i < messageConverters.size(); i++) {
            HttpMessageConverter<?> h = messageConverters.get(i);
            if (h instanceof MappingJackson2XmlHttpMessageConverter) {
                xml = i;
            } else if (h instanceof MappingJackson2HttpMessageConverter) {
                json = i;
            }
        }
        Collections.swap(template.getMessageConverters(), xml, json);

        return template;
    }

[Solved] SyntaxError:JSON.parse:unexpected character at line 1 column 1 of the JSON data

Controller code:

Front end Ajax request code:

The status code 200 indicates that the request is successful, but the pop-up window (data returned by the server) cannot be received

Question tips:

SyntaxError:JSON. parse:unexpected character at line 1 column 1 of the JSON data

It is speculated that there was an error in parsing JSON data. The server wanted to use the string as JSON, but the format conversion failed

The reason is that I set the datatype in the Ajax request to “JSON”. JQuery will convert the string in the resp to JSON format according to this, but the conversion fails. Just comment out this line.

[Solved] SpringBoot Error: HttpMediaTypeNotSupportedException: Content type ‘application/json‘ not supported

HttpMediaTypeNotSupportedException: Content type ‘application/json;charset=UTF-8’ not supported
Error:

{
    "timestamp": "2021-12-13T11:49:33.305+00:00",
    "status": 415,
    "error": "Unsupported Media Type",
    "path": "/api/v1/product/add"
}

If you are sure that there is no problem with your parameters, it is likely that the problem lies in your @requestbody AAA a
the problem I encounter here is that protobuf is used, but no corresponding bean is injected, resulting in an error. Just add the following code to the application:

PS: protobufmodule is our own extended com fasterxml.jackson.databind.Module class, it’s inconvenient to put it out. You can consult the data by yourself

    @Bean
    ProtobufJsonFormatHttpMessageConverter protobufHttpMessageConverter() {
        return new  ProtobufJsonFormatHttpMessageConverter();
    }

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jsonCustomizer() {
        return builder -> builder.serializationInclusion(JsonInclude.Include.NON_NULL)
                .modules(new ProtobufModule(), new JavaTimeModule());
    }

[Solved] HttpMessageNotReadableException: JSON parse error: Unrecognized field “xxxx“

Environment: springboot 2.0 9 (this problem does not exist in the latest version of springboot)

Problem Description:

Prompt when post requests @requestbody to receive objects

org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Unrecognized field "aaaaa" (class com.ex.application.model.RiskAudit), not marked as ignorable; nested exception is com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "aaaaa" (class com.ex.application.model.RiskAudit), not marked as ignorable (25 known properties: "xxx"])
 at [Source: (PushbackInputStream); line: 4, column: 15] (through reference chain: com.ex.application.model.RiskAudit["aaaaa"])

AAAAA is not a property of the riskaudit object

Problem Fix:

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Autowired
    private Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder;

	/**
     * Ignore unmatched properties or add @JsonIgnoreProperties(ignoreUnknown = true) annotation to the response object
     * @param converters
     */
    @Bean
    public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        converter.setObjectMapper(objectMapper);
        return converter;
    }

    /**
     * Format the date (I used LocalDateTime locally, LocalDateTime will become an object when data is obtained without this method)
     * @param converters
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        ObjectMapper mapper = jackson2ObjectMapperBuilder.build();
        mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        converters.add(0, new MappingJackson2HttpMessageConverter(mapper));
    }

}

[Solved] ajax Error: Uncaught SyntaxError: Unexpected end of JSON input

To record, the Ajax request is as follows:

		let xhr = new XMLHttpRequest();
        xhr.open("get","https://music.kele8.cn/search");
        xhr.send();
       
        xhr.onreadystatechange = function () {
            // Determine when the Ajax status code is 4 
            if (xhr.status==200) {
                // Get the response data from the server side
                let ans = JSON.parse(xhr.responseText);
                console.log(ans);
            }
			else {
				console.log("Request failed");
			}
        }

If you ensure that the data returned in the background is correct, the get request can be opened in the browser address bar to see the data in JSON format, but the console reports an error and the data is also obtained, it may be that you lack a judgment

Look at the following code:

let xhr = new XMLHttpRequest();
xhr.open("get", "https://music.kele8.cn/search?keywords="+str);
xhr.send();
                        
xhr.onreadystatechange = function () {
     if(xhr.readyState == 4) {
            if(xhr.status == 200) {
                let arr = xhr.responseText;
                let ctype = xhr.getAllResponseHeaders("content-type");
                if(ctype.indexOf("json") > -1) {
                         let res = JSON.parse(arr);
                         console.log(res);
                 }
                 else {
                        console.log(arr);
                }
          }
          else {
                reject('Request failed');
          }
      }
}

It seems that you need to judge XHR in the onreadystatechange event If the readyState attribute is not judged, an error will be reported by JSON

[Solved] Error creating bean with name ’emf’ defined in org.ngrinder.infra.config.DatabaseConf

This similar problem has been encountered several times, but you can still find the error every time you report an error. When reporting an error, think about what you modified earlier, and then go to see if the corresponding code has the same path. Or attribute problems. But I can’t find the error report this time. The previous version before my modification can still be started. When I came to work the next day, I reported an error as soon as it was started. It has not been solved yet. If it is solved, the answer will be pasted. The following error reasons:

Code text:

01-Dec-2021 18:58:11.804 信息 [RMI TCP Connection(3)-127.0.0.1] org.apache.catalina.core.ApplicationContext.log Spring WebApplicationInitializers detected on classpath: [org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration$JerseyWebApplicationInitializer@b0ebd27]
01-Dec-2021 18:58:11.953 信息 [RMI TCP Connection(3)-127.0.0.1] org.apache.catalina.core.ApplicationContext.log Initializing Spring root WebApplicationContext
01-Dec-2021 18:58:15.892 严重 [RMI TCP Connection(3)-127.0.0.1] org.apache.catalina.core.StandardContext.listenerStart 异常将上下文初始化事件发送到类的侦听器实例.[org.springframework.web.context.ContextLoaderListener]
		at org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager.preparePersistenceUnitInfos(DefaultPersistenceUnitManager.java:470)
		at org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager.afterPropertiesSet(DefaultPersistenceUnitManager.java:424)
		at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:310)
		at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:319)
		at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1637)
		at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574)
		... 59 more
01-Dec-2021 18:58:15.911 信息 [RMI TCP Connection(3)-127.0.0.1] org.apache.catalina.core.ApplicationContext.log Closing Spring root WebApplicationContext
	org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'emf' defined in org.ngrinder.infra.config.DatabaseConfig: Invocation of init method failed; nested exception is java.lang.IllegalStateException: Conflicting persistence unit definitions for name 'ngrinder': file:/D:/zaixianStudy/0server/apache-tomcat-8.5.69/webapps/ngrinder-web/WEB-INF/lib/ngrinder-controller-3.4.4.jar, file:/D:/zaixianStudy/0server/apache-tomcat-8.5.69/webapps/ngrinder-web/WEB-INF/classes
		at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1578)
		at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545)
		at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
		at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
		at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
		at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
		at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
		at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1054)
		at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:829)
		at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538)
		at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:444)
		at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:326)
		at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
		at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4763)
		at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5232)
		at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
		at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:755)
		at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:729)
		at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:695)
		at org.apache.catalina.startup.HostConfig.manageApp(HostConfig.java:1775)
		at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
		at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
		at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
		at java.lang.reflect.Method.invoke(Method.java:498)
		at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:291)
		at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
		at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
		at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:483)
		at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:431)
		at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
		at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
		at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
		at java.lang.reflect.Method.invoke(Method.java:498)
		at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:291)
		at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
		at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
		at com.sun.jmx.remote.security.MBeanServerAccessController.invoke(MBeanServerAccessController.java:468)
		at javax.management.remote.rmi.RMIConnectionImpl.doOperation(RMIConnectionImpl.java:1468)
		at javax.management.remote.rmi.RMIConnectionImpl.access$300(RMIConnectionImpl.java:76)
		at javax.management.remote.rmi.RMIConnectionImpl$PrivilegedOperation.run(RMIConnectionImpl.java:1309)
		at java.security.AccessController.doPrivileged(Native Method)
		at javax.management.remote.rmi.RMIConnectionImpl.doPrivilegedOperation(RMIConnectionImpl.java:1408)
		at javax.management.remote.rmi.RMIConnectionImpl.invoke(RMIConnectionImpl.java:829)
		at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
		at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
		at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
		at java.lang.reflect.Method.invoke(Method.java:498)
		at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:357)
		at sun.rmi.transport.Transport$1.run(Transport.java:200)
		at sun.rmi.transport.Transport$1.run(Transport.java:197)
		at java.security.AccessController.doPrivileged(Native Method)
		at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
		at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:568)
		at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:826)
		at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:683)
		at java.security.AccessController.doPrivileged(Native Method)
		at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:682)
		at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
		at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
		at java.lang.Thread.run(Thread.java:748)
	Caused by: java.lang.IllegalStateException: Conflicting persistence unit definitions for name 'ngrinder': file:/D:/zaixianStudy/0server/apache-tomcat-8.5.69/webapps/ngrinder-web/WEB-INF/lib/ngrinder-controller-3.4.4.jar, file:/D:/zaixianStudy/0server/apache-tomcat-8.5.69/webapps/ngrinder-web/WEB-INF/classes

The problem has been solved. Let’s talk about my handling method. I won’t talk about bullshit. I’ve met those interfaces with the same URL, no annotation, the same method name, wrong package, different versions, repeated POM files or inconsistent versions, and what reset projects empty Maven and download again. I’ve met them many times, I’ve tried it all. The answers on the Internet are the same, copy around. My situation is like this. I can run on the first day, but I can’t do it on the second day. I don’t have a clue about the error reported. I checked the GIT code again and again and found that there is nothing wrong and I can’t start. So I did the following work:

1. Find the local tomcat, delete the jar package in webapp and the compiled project file, delete the Tomcat configuration in the project, and reconfigure it

2. Check whether Maven is configured correctly, whether Maven is its own, whether the settings.xml file is correct, and the warehouse. There are many local versions of tomcat, Maven and JDK. I downloaded a lot to test the difference between versions before. After checking, click the navigation bar on the right, circle, refresh and brush several times

3. Click File >>>> ProjectStructure>>> Modules, delete all and reintroduce

4. Check whether the artifacts are correct, and there must be all of them

5. On the right navigation bar, refresh maven, clear, complex, package and run, which solves my problem.

The above is my solution. I have no problem with the code. If there is a problem with the code, don’t use it