I am learning lwc and got stuck in the getting data from Apex class. Below is the code
JS:
import { LightningElement } from 'lwc';
import getAccountList from '@salesforce/apex/AccountController.getAccountList';
export default class AccountComponent extends LightningElement {
accounts;
error;
handleLoad() {
getAccountList()
.then((result) => {
alert(JSON.stringify(result));
this.accounts = result;
this.error = undefined;
})
.catch((error) => {
alert(JSON.stringify(error));
this.error = error;
this.accounts = undefined;
});
}
}
Apex Class:
public with sharing class AccountController {
@AuraEnabled(cacheable=true)
public static List<Account> getAccountList() {
return [SELECT Id, Name FROM Account WITH SECURITY_ENFORCED LIMIT 10];
}
}
I am getting below error in an alert box:
{"ok":false,"status":400,"statusText":"Bad Request","body":{}}
But in Chrome->Network tab, I am getting 500 Internal server error with below message:
error parsing apex response: Unexpected token * in JSON at position 0
Any idea what I am doing wrong?
Best Answer
It looks like you're using the Local Development Server. This feature requires a Scratch Org in order to run Apex. Make sure you've started the Local Development Server, created a Scratch Org, and pushed the source code to the server in order to run the code. Alternatively, deploy this code to an org so you can run it in a Salesforce environment. Please note the limitations of the Local Development Server.