Categories
discuss

Unexpected token O in JSON at position 0 when I query an API

I know that the question is findable on the forum but no answer works for me. I have an angular service that calls a nodeJS API like this:

Angular service

public createUser(pUser: User): Observable<User> {
    var url = "http://localhost:5000/users";
    var json = JSON.stringify(pUser)
    return this.http.post<User>(url, pUser)
  }

NodeJS API

router.post('/', (req, res) => {
    console.log(req.body)
    User.create({ email: req.body.email, password: req.body.password })
    res.sendStatus(200);
});

The API is well called, the insertion into database works, but I have this message in the browser:

SyntaxError: Unexpected token O in JSON at position 0

The status of the request is 200 on return but the error is still present in the browser

I do not know if the problem comes from the front end or the backend.

After doing some research, I try to parse my object before sending it. I try to stringify too.

Without success

Is this someone would have the solution? thank you very much

Answer

This error occurs when you try to parse invalid JSON.

Due to the default response type for angular is JSON and the default response of code 200 is ‘OK’. You have to adapt one of them.

You can change the response type to text like this:

this.http.post<User>(url, pUser, {responseType: 'text'});

Or you return a JSON object:

res.status(200).send({ status: 'OK'});
Categories
discuss

New-added Maven plugin becomes red in IntelliJ

I’m following this guideline for a Maven plugin, after which I’ve added the following:

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-release-plugin</artifactId>
  <version>2.5.3</version>
</plugin>

maven-release-plugin & 2.5.3 are both red. I’m using a local Maven repository. How can I update it? Do I need to install anything so that IntelliJ can find it? I’m new to Maven and would appreciate being pointed in the right direction.

Answer

You have to add the following in Maven pom.xml.

<build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-release-plugin</artifactId>
        <version>2.5.3</version>
      </plugin>
    </plugins>
  </build>

Once added , wait for 2 mins in Intellij Idea based upon the network speed. Still does not work, click on the right side of Intellij Idea having a tab “Maven” and click refresh button. See the picture below.

enter image description here

Categories
discuss

How can I mock axios API calls? with using jest

Hi I’m testing my vuex action async function which is calling api via axios, but I have some problem that it show error like this ” TypeError: Cannot destructure property data of ‘undefined’ or ‘null’.

  35 |     commit('storeSearchValue', name);
  36 |     const url = process.env.VUE_APP_URL_API_News + '/news' + '?q=' + name;
> 37 |     const { data } = await axios.get(url);"

my vue js code is

 async updateSearchValue({ commit }, name) {
    commit('storeSearchValue', name);
    const url = process.env.VUE_APP_URL_API_News + '/news' + '?q=' + name;
    const { data } = await axios.get(url);
    commit('storeNewsData', data.result);
  },

and this is test file,

import actions from '@/store/modules/data/data-actions.js'
import VueRouter from 'vue-router';
import axios from 'axios';

import {
  createLocalVue
} from '@vue/test-utils';
const localVue = createLocalVue();
localVue.use(VueRouter);
jest.mock('axios');

describe('', () => {
  test('updateSearchValue', async () => {
    const commit = jest.fn()
    const name = jest.fn()

    await actions.updateSearchValue({
      commit,
      name
    })

    expect(commit).toHaveBeenCalledWith('updateSearchValue', name)
  })

})

Answer

You have used jest.mock('axios') which is automatically generating mock for module and it will create jest.fn() for axios.get, but it will return undefined unless you tell it otherwise

Since you’re expecting it to return a resolved promise with object with data property you can use:

axios.get.mockReturnValue(Promise.resolve({
  data: 'mock data'
});

or the short-hand:

axios.get.mockResolvedValue({ data: 'mock data' });

Also check this answer

Categories
discuss

Enqueue javascript with type=”module”

I want to use countUp.js on my custom theme in WordPress.

When I add the file with wp_enqueue_script(), I get an error:

Uncaught SyntaxError: Unexpected token 'export'

I’ve read that it can be fixed setting on the <script> label type="module", but I don’t know how to do that, as that option doesn’t exist in wp_enqueue_script()

Anyone can hel me?

Answer

One can add attributes to a script by applying filter ‘script_loader_tag‘.

Use add_filter('script_loader_tag', 'add_type_attribute' , 10, 3); to add the filter.

Define the callback function like the example given on the link above:

function add_type_attribute($tag, $handle, $src) {
    // if not your script, do nothing and return original $tag
    if ( 'your-script-handle' !== $handle ) {
        return $tag;
    }
    // change the script tag by adding type="module" and return it.
    $tag = '<script type="module" src="' . esc_url( $src ) . '"></script>';
    return $tag;
}
Categories
discuss

Gradle 6 with Intellij – refresh fails

I have a gradle 6.0 project with Spring 2.1.7.

When I try to refresh all gradle projects from intellij enter image description here

I got an error:

Unable to load class ‘org.gradle.api.internal.plugins.DefaultConvention’. Possible causes for this unexpected error include:

  • Gradle’s dependency cache may be corrupt (this sometimes occurs after a network connection timeout.) Re-download dependencies and sync project (requires network)
  • The state of a Gradle build process (daemon) may be corrupt. Stopping all Gradle daemons may solve this problem. Stop Gradle build processes (requires restart)
  • Your project may be using a third-party plugin which is not compatible with the other plugins in the project or the version of Gradle requested by the project.
In the case of corrupt Gradle processes, you can also try closing the IDE and then killing all Java processes.

I use intellij v 2018.3.4 and I’ve configured it to use the gradle wrapper:

enter image description here

The gradle-wrapper.properties looks like this:

distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https://services.gradle.org/distributions/gradle-6.0-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

If I run the gradle wrapper from command line there are not problems. Also If I trigger a gradle task (build, clean …) from Intellij I have no errors.

I have another wired issue that could be related to this one. In my build.gradle I use spring boot 2.1.7 and If I run my jar from the command line I can see from the Spring Boot banner the configured version 2.1.7. Instead If I run the application form Intellij I see that It is using Spring Boot 2.0.8, also if I expand the External libraries tree I see: enter image description here

the build.gradle looks like:

buildscript {
 ext {
   springBootVersion = "2.1.7.RELEASE"
   springBootDepManagementVersion = "1.0.8.RELEASE"
 }
}
plugins {
 id 'idea'
 id 'java'
 id "io.spring.dependency-management" version "${springBootDepManagementVersion}"
 id 'org.springframework.boot' version "${springBootVersion}"
}
dependencies {
   implementation 'org.springframework.boot:spring-boot-starter-web'
   ....
}

Thank you

Answer

I solved the problem downgrading the gradle wrapper to 5.6.4. Apparently my Intellij version does not support gradle 6.0.0

Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..