Laravel + Vue Error in render: "SyntaxError: Unexpected token u in JSON at position 0" - json

I have a Laravel application with Vue js and until a while ago it was working perfectly. Now when I go to any page that uses Vue js this error appears: [Vue warn]: Error in render: "SyntaxError: Unexpected token u in JSON at position 0".
When I reload the page by clearing the cache (Control + Shift + R on Mac OS) it works again, but when I update without this command the error appears again.
PS: I didn't do any package updates for both laravel and npm, it just stopped working out of nowhere.

Try this in the console:
JSON.parse(undefined)
Here is what you will get:
Uncaught SyntaxError: Unexpected token u in JSON at position 0
at JSON.parse (<anonymous>)
at <anonymous>:1:6
In other words, your app is attempting to parse undefined, which is not valid JSON.
There are two common causes for this. The first is that you may be referencing a non-existent property (or even a non-existent variable if not in strict mode).
window.foobar = '{"some":"data"}';
JSON.parse(window.foobarn) // oops, misspelled!
The second common cause is failure to receive the JSON in the first place, which could be caused by client side scripts that ignore errors and send a request when they shouldn't.
Make sure both your server-side and client-side scripts are running in strict mode and lint them using ESLint. This will give you pretty good confidence that there are no typos.
Sometime it is becaseu of this let data = JSON.parse(this.response); so try to change it to
let data = JSON.parse(this.responseText);
I really did was change this.response to this.responseText

Related

Exception: '<' is an invalid start of a value

I have a Blazor Webassembly project with a controller method as follows:
[HttpGet]
public async Task<List<string>> GetStatesForProfile()
{
IConfigurationSection statesSection = configuration.GetSection("SiteSettings:States");
var sections = statesSection.GetChildren();
var states = statesSection.GetChildren().Select(s => s.Key).ToList<string>();
return states;
}
The razor page calls this method:
private async Task<bool> GetStatesModel()
{
try
{
States = await http.GetJsonAsync<List<string>>("api/account/getstatesforprofile");
...
}
catch (Exception ex)
{
Console.WriteLine($"Exception: {ex.Message}, Inner: {ex.InnerException.Message}");
}
I get this Exception:
Exception: '<' is an invalid start of a value.
I read these values from appsettings.json file, And there is no '<' in values.
{
"SiteSettings": {
"States": {
"New York": ["NYC"],
"California": ["Los Angeles", "San Francisco"]
}
}
Also I put a breakpoint in the controller method and it doesn't hit.
What is this error? Is it from parsing json? and how to resolve this?
I had a very similar problem.
In the end it turned out that my browser had cached the HTML error page (I guess I had some problems with the code when I first tried it). And no matter how I tried fixing the code I still only got the error from cache. Clearing my cache also cleared the problem.
It happens when you're trying to access an API that doesn't exist. You have to check your API project connectionstring under AppSettings and make sure it's correct and running. If it's a Blazor project, you can set it as your default project, execute and see if you get a json response.
Most probably the response you are receiving is html instead of actual JSON format for the endpoint you are requesting. Please check that.
An as HTML usually starts with <html> tag, the JSON validator fails on the very first character.
You should also clear any cache, that might be interfering with the returned data. (this has helped people resolve this same issue)
I know this is an old question, but it's one of the top results when Googling the error.
I've just spent more time than I care to admit to tracking down this error. I had a straightforward Blazor hosted app, basically unchanged from the template. It worked just fine when run locally, but when published to my web host API calls failed. I finally figured out that the problem was that I was running the publish from the Client project. When I changed to the Server project it worked properly.
Hopefully my long frustration and slight stupidity will save someone else making a similar mistake.
Seems like your api is not not accessible and its returning error HTML page by default.
You can try below solution:-
I think you are using httpclient to get data to blazor application.
If you have separate projects in solution for blazor and web api,
currently your startup application may set to run blazor project only.
Change startup projects to multiple (blazor and web api app) and give httpClient url in startup of blazor application, as webApi application url, that may solve your issue.
This error indicates a mismatch of the project targeting framework version and installed runtime on the machine. So make sure that the target framework for your project matches an installed runtime - this could be verified by multiple means; one of them is to check out the Individual Components tab of the Visual Studio Installer and lookup the target version.
E.g., there is the TargetFramework attribute in the proj file:
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
Then launch the Visual Studio Installer, click Modify, and visit the Individual Components tab:
Install the missing runtime (.NET 5 Runtime in this case) and you're good to go.
I got the same error. Red herring. use your browser or postman to check your api endpoint is returning the json data and not some HTML. In my case my "api/companytypes" had a typo.
private CompanyType[] companytypesarray;
private List<CompanyType> CompanyTypeList;
private List<CompanyType> CompanyTypeList2;
public async Task<bool> LoadCompanyTypes()
{
//this works
CompanyTypeList = await Http.GetFromJsonAsync<List<CompanyType>>("api/companytype");
//this also works reading the json into an array first
companytypesarray = await Http.GetFromJsonAsync<CompanyType[]>("api/companytype");
CompanyTypeList2 = companytypesarray.ToList();
return true;
}
I know this is an old question, but I had the same problem. It took some searching, but I realized that the return data was in XML instead of JSON.
I'm assuming your "http" variable is of type HttpClient, so here's what I found worked for me.
By setting the "Accept" header to allow only JSON, you avoid a miscommunication between your app and the remote server.
http.DefaultRequestHeaders.Add("Accept", "application/json");
States = await http.GetJsonAsync<List<string>>("api/account/getstatesforprofile");
I had the same issue when passing in an empty string to a controller method. Creating a second controller method that doesn't accept any input variables, and just passing an empty string to the first method helped to fix my problem.
[HttpGet]
[ActionName("GetStuff")]
public async Task<IEnumerable<MyModel>> GetStuff()
{
return await GetStuff("");
}
[HttpGet("{search}")]
[ActionName("GetStuff")]
public async Task<IEnumerable<MyModel>> GetStuff(string search)
{
...
}
Versions of package
Try to update your packages to old or new version. In my case, system.net.http.json is updated from 6.0 to 5.0
Likely you are using an Asp.NetCore hosted WASM application. By default the client's App.razor has something similar to:
<CascadingAuthenticationState>
<Router AppAssembly="#typeof(Program).Assembly">
<Found Context="routeData">
<AuthorizeRouteView DefaultLayout="#typeof(MainLayout)"
RouteData="#routeData">
<NotAuthorized>
<RedirectToLogin />
</NotAuthorized>
<Authorizing>
<Loading Caption="Authorizing..."></Loading>
</Authorizing>
</AuthorizeRouteView>
</Found>
<NotFound>
<LayoutView Layout="#typeof(MainLayout)">
<p>Sorry, there's nothing at this address.</p>
</LayoutView>
</NotFound>
</Router>
</CascadingAuthenticationState>
Herein lies the problem. Since the Client and Server share the same base address, when the application cannot find "api/account/getstatesforprofile" it gives you the client's "Sorry, there's nothing at the address" page. Which is of course HTML.
I have not found the solution to this issue, but I am working on it and will reply once I find an issue.
I was having the same problem,
"JsonReaderException: '<' is an invalid start of a value."
In my case the url for the REST service was wrong.
I was using the URL from the client project. Then I looked at the Swagger screen,
https://localhost:44322/swagger/index.html
and noticed the right URL should start with "44322"...
Corrected, worked.
In my case, I had a comma (,) written mistakenly at the beginning of the appsettings.json file ...
Just check your file and verify
///////
my error details
//////
System.FormatException HResult=0x80131537 Message=Could not parse the JSON file.
Source=Microsoft.Extensions.Configuration.Json StackTrace: at line 16 This exception was originally thrown at this call stack: [External Code] Inner Exception 1: JsonReaderException: ',' is an invalid start of a value. LineNumber: 0 | BytePositionInLine: 0.
////
For me, most of the time it is the #lauri-peltonen answer above. However, now and again, depending on who wrote the controller I have found that this will work in Swagger but not when you call it via the client (at least in this Blazor project we are on.)
[HttpGet]
[Route("prog-map-formulations")]
public async Task<List<GetProgramMapFormulationsResult>> GetProgramMapFormulations(int formulationId)
{
...
}
It sends the request as:
api/formulation-performance-program-map/analytical-assoc-values?formulationId=1
And I get results in Swagger but failes with the '<' OP error.
When I change ONLY the route to:
[HttpGet]
[Route("prog-map-formulations/{formulationId:int}")]
public async Task<List<GetProgramMapFormulationsResult>> GetProgramMapFormulations(int formulationId)
{
...
}
It sends the request as:
api/formulation-performance-program-map/analytical-assoc-values/1
And this works in both Swagger as well as from the Client side in Blazor.
Of course, once updated, I did have to clear the cache!
If you delete "obj" folder in your directory then clean the solution and rebbuild it the exception will be resolved
In all these, there is two things that was my issue and realized, first off was that Route[("api/controller")] instead of Route[("api/[controller]")], that is missing square brackets. In the second exercise I was doing, with the first experience in mind, was from the name of the database. The database had a dot in the name (Stock.Inventory). When I change the database name to StockInventory it worked. The second one I am not so sure but it worked for me.

Proxy request on firebase

I have created a project using Ionic and deployed it as a PWA to firebase. I have got around CORS utilising a proxy to call google maps api sevices. This works locally however once deployed this is no longer the case.
The response I am getting on the server is:
SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)
at XMLHttpRequest.l (https://atomic-affinity-127705.firebaseapp.com/build/vendor.js:1:312114)
at t.invokeTask (https://atomic-affinity-127705.firebaseapp.com/build/polyfills.js:3:15660)
at Object.onInvokeTask (https://atomic-affinity-127705.firebaseapp.com/build/vendor.js:1:26996)
at t.invokeTask (https://atomic-affinity-127705.firebaseapp.com/build/polyfills.js:3:15581)
at r.runTask (https://atomic-affinity-127705.firebaseapp.com/build/polyfills.js:3:10834)
at e.invokeTask [as invoke] (https://atomic-affinity-127705.firebaseapp.com/build/polyfills.js:3:16794)
at p (https://atomic-affinity-127705.firebaseapp.com/build/polyfills.js:2:27648)
at XMLHttpRequest.v (https://atomic-affinity-127705.firebaseapp.com/build/polyfills.js:2:27893)
"Http failure during parsing"
When looking at the text field I get the contents of my index.html page being parsed. Starting with the Doctype explaining why the error fails on <.
Ionic.config.json has the following:
"proxies": [{
"path": "/api",
"proxyUrl": "https://maps.googleapis.com/"
}]
and is called as such:
/api/maps/api/place/nearbysearch/ ....etc
Any help would be greatly appreciated.
For those that are interested in this solution, I ended up utilising the js libraries provided by Google. The alternative to get around this is create a functions set on firebase and run express to do the calls for with the appropriate CORS headers however I didn't want to add extra calls in.

Wakanda server start JSON error unexpected EOF

WAK 1.1.3 - during solution load, get a backend error:
[Backend] Error
[Backend] SyntaxError: JSON Parse error: Unexpected EOF
But it is not clear what file has this issue. How to most efficiently isolate this? I see nothing in the logs. The application has been running stably. I assume this is in a method, but am not finding it after a thorough search.
Thanks for guidance.
Kirk
Unexpected EOF error could be as small as forgetting to close function body with a right curly bracket.
I recommend first checking all the code on the backend you have modified since the last successful restart.
Secondly, since this occurs during solution load, the error is likely in bootstrap code including login listener. Or in model.js. You could try comment out all code in bootstrap.js or model.js see if the solution can load.

Appcelerator message = "JSON Parse error: Unexpected identifier \"undefined\"";

I am adding new features to an app I wrote last years and is working now ... I just port the code from Appcelerator (3.2...) to the Appcelerator Studio 5.2.0.GA SDK ... and I have spent 2 days trying to figure out why code that currently works on an app in the app store is not working in the SDK 5.2.0 environment
I keep getting the above error .. I am positive the url is correct and working
This line of code works now in the app in the store and in 3.1... but is not working in 5.2.0
var jsonObject = JSON.parse(this.responseText);
It gives the above error
"JSON Parse error: Unexpected identifier \"undefined\"";
I have read their site and searched for a solution ... Thanks
entire Block
Try one thing:
Open this site and put your response data in which you are getting error https://jsonformatter.curiousconcept.com
After parsing the same data on the above site, you can check whether the problem is really in your Titanium code or in your data.
Also check whether you are really getting any response data or not.
If it does not help, then please share some necessary source code
Thanks

Using Ext JS with my HTML Files

I have an application uses Spring Security 3(has a Jackson Marshaller) runs on a Tomcat 7. I designed my application with Jquery and it runs well. I designed a login page with Ext JS and after successful login it redirects to index.html. However it gives an error and can't redirect because when server sends HTML file it comes into that function at Ext JS:
Ext.util.JSON = new (function(){
...
doDecode = function(json){
return eval("(" + json + ")");
},
...
I wants to render it as a JSON response and gives an error as usual. How to solve it?
PS: It gives that on Firebug:
syntax error
[Break On This Error] (<!DOCTYPE html>
The server is not returning valid JSON. Its look as if it is returning a HTML page (perhaps a friendly error page). If you follow the stack trace up its probably Ext.decode response.responseText (inspect this you'll see whats returned although not the best way)
First step would be to investigate the request in the Net panel in Firebug or Chrome, look at the request and response headers and content this will point you in the right direction. Please please please do not resolve this problem without first learning to use a client side browser debugger (Firebug or Chrome Dev Tools or even Safari) such as walking the stack on break on error, break on XHR, inspect the XHR headers and response etc.. not just watching the console window.
You might be able to fix this continuing blind but you'll pay heavily again next time.