Syntax error unexpected token laravel

Laravel Mix Version: Tried both, 1.7.2 and 2.0.0 (npm list --depth=0) Node Version (node -v): v8.0.0 NPM Version (npm -v): 5.6.0 OS: Ubuntu 16.04.3 LTS Description: Background: I think about switch...
  • Laravel Mix Version: Tried both, 1.7.2 and 2.0.0 (npm list --depth=0)
  • Node Version (node -v): v8.0.0
  • NPM Version (npm -v): 5.6.0
  • OS: Ubuntu 16.04.3 LTS

Description:

Background: I think about switching my project from AngularJS and Lumen to VueJS and Laravel.
Thus, I set up a test project using laravel installer and vue preset. I added a tree/hierarchy/menu-plugin (bosket) and tried to use custom html in the display() function. The bosket doc uses something like this:

display: (item, inputs) =>
    <strong>{ item.label }</strong>,

But then I get the Syntax Error

ERROR in ./node_modules/babel-loader/lib?{"cacheDirectory":true,"presets":[["env",{"modules":false,"targets":{"browsers":["> 2%"],"uglify":true}}]],"plugins":["transform-object-rest-spread",["transform-runtime",{"polyfill":false,"helpers":false}]]}!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./resources/assets/js/components/ExampleComponent.vue
Module build failed: SyntaxError: Unexpected token (31:12)

I «fixed» this by adding a custom .babelrc file, but then I get errors when loading the page.
.babelrc:

{
    "presets": [
        [ "env", { "modules": false } ]
    ],
    "plugins": [
        "transform-vue-jsx",
        "transform-object-rest-spread",
        "transform-class-properties",
    ]
}

Error:

 [Vue warn]: Error in render: "ReferenceError: h is not defined"

found in

---> <TreeViewNode>
       <WithTransitionTreeViewNode>
         <TreeView>
           <WithLabelsTreeView>
             <WithListenerWithLabelsTreeView>
               <WithListenerWithListenerWithLabelsTreeView>
                 <ExampleComponent> at resources/assets/js/components/ExampleComponent.vue
                   <Root>

Steps To Reproduce:

  1. Install Laravel with laravel-mix and vue preset
  2. Install tree plugin (npm i --save @bosket/core @bosket/tools @bosket/vue)
  3. Install deps (npm i --save-dev babel-helper-vue-jsx-merge-props)
  4. Add ExampleComponent.vue (code attached)
  5. Run php artisan serve and npm run watch
  6. Open localhost:8000 and check js console

laravel-test.zip

Syntax error unexpected token laravel

public function Store(Request $request)< n

This is correct: n

public function Store(Request $request)n<n $validateData = $request->validate([n ‘class_name’ => ‘required|unique:sclasses|max:25’n ]);nn Sclass::create($validateData);nn return response(‘Student Class Inserted Successfull’);n>n n

Your error comes from this line: n

This is correct: n

public function Store(Request $request)n<n $validateData = $request->validate([n ‘class_name’ => ‘required|unique:sclasses|max:25’n ]);nn Sclass::create($validateData);nn return response(‘Student Class Inserted Successfull’);n>n n

Your error comes from this line: n

Laravel 9 is here, and along with it comes a wide array of useful new features and tweaks. This includes an improved accessor/mutator API, better support for Enum casting, forced scope bindings, a new database engine for Laravel Scout, and so much more.

If you have 45 minutes to spare, I’ll show you everything you need to know to get up to speed. «,»path»:»/series/whats-new-in-laravel-9″,»strippedBody»:»Laravel 9 is here, and along with it comes a wide array of useful new features and tweaks. This includes an improved accessor/mutator API, better support for Enum casting, forced scope bindings, a new database engine for Laravel Scout, and so much more.If you have 45 minutes to spare, I’ll show you everything you need to know to get up to speed.»,»thumbnail»:»https://ik.imagekit.io/laracasts/series/thumbnails/whats-new-in-laravel-9.png»,»large_thumbnail»:»https://laracasts.s3.amazonaws.com/series/thumbnails/social-cards/whats-new-in-laravel-9.png»,»svgThumbnail»:»https://ik.imagekit.io/laracasts/series/thumbnails/svg/whats-new-in-laravel-9.svg»,»slug»:»whats-new-in-laravel-9″,»episodeCount»:11,»difficultyLevel»:»Intermediate»,»customUrl»:»whatsnewinlaravel.com»,»version»:»Laravel 9″,»version_notes»:null,»complete»:1,»wallpaper»:»https://laracasts.nyc3.digitaloceanspaces.com/series/wallpapers/Whats-New-in-Laravel-9.zip»,»archived»:0,»runTime»:»44m»,»taxonomy»:<«name»:»Frameworks»,»path»:»https://laracasts.com/browse/frameworks»>,»hasChapters»:false,»isLarabit»:0,»isCreatorSeries»:0,»progress»:<«started»:false,»completionPercentage»:0,»episodesCompleted»:0,»completed»:false,»nextEpisodePosition»:1>,»lastUpdated»:»Feb 8, 2022″>,<«id»:142,»className»:»Laracasts\Series»,»title»:»Laravel 8 From Scratch»,»body»:»

rnWe don’t learn tools for the sake of learning tools. Instead, we learn them because they help us accomplish a particular goal. With that in mind, in this series, we’ll use the common desire for a blog — with categories, tags, comments, email notifications, and more — as our goal. Laravel will be the tool that helps us get there. Each lesson, geared toward newcomers to Laravel, will provide instructions and techniques that will get you to the finish line. rn rn

Источник

Когда встречается. Допустим, вы пишете цикл for на JavaScript и вспоминаете, что там нужна переменная цикла, условие и шаг цикла:

for var i = 1; i < 10; i++ {
<span style="font-weight: 400;">  // какой-то код</span>
<span style="font-weight: 400;">}</span>

После запуска в браузере цикл падает с ошибкой:

❌ Uncaught SyntaxError: Unexpected token ‘var’

Что значит. Unexpected token означает, что интерпретатор вашего языка встретил в коде что-то неожиданное. В нашем случае это интерпретатор JavaScript, который не ожидал увидеть в этом месте слово var, поэтому остановил работу.

Причина — скорее всего, вы пропустили что-то из синтаксиса: скобку, кавычку, точку с запятой, запятую, что-то подобное. Может быть, у вас была опечатка в служебном слове и язык его не распознал.

Что делать с ошибкой Uncaught SyntaxError: Unexpected token

Когда интерпретатор не может обработать скрипт и выдаёт ошибку, он обязательно показывает номер строки, где эта ошибка произошла (в нашем случае — в первой же строке):

Интерпретатор обязательно показывает номер строки, где произошла ошибка Uncaught SyntaxError: Unexpected token

Если мы нажмём на надпись VM21412:1, то браузер нам сразу покажет строку с ошибкой и подчеркнёт непонятное для себя место:

Строка с ошибкой Uncaught SyntaxError: Unexpected token

По этому фрагменту сразу видно, что браузеру не нравится слово var. Что делать теперь:

  • Проверьте, так ли пишется эта конструкция на вашем языке. В случае JavaScript тут не хватает скобок. Должно быть for (var i=1; i<10; i++) {}
  • Посмотрите на предыдущие команды. Если там не закрыта скобка или кавычка, интерпретатор может ругаться на код немного позднее.

Попробуйте сами

Каждый из этих фрагментов кода даст ошибку Uncaught SyntaxError: Unexpected token. Попробуйте это исправить.

if (a==b) then  {}
function nearby(number, today, oneday, threeday) {
  if (user_today == today + 1 || user_today == today - 1)
    (user_oneday == oneday + 1 || user_oneday == oneday - 1)
      && (user_threeday == threeday + 1 || user_threeday == threeday - 1)
  return true
  
  else
     return false
}
var a = prompt('Зимой и летом одним цветом');
if (a == 'ель'); {
  alert("верно");
} else {
  alert("неверно");
}
alert(end);

После того, как в моем проекте Laravel 9 я запустил composer update, я столкнулся с этим сообщением об ошибке:

Writing lock file
Installing dependencies from lock file (including require-dev)
Package operations: 0 installs, 1 update, 1 removal
  - Downloading fruitcake/laravel-cors (v3.0.0)
  - Removing asm89/stack-cors (v2.1.1)
  - Upgrading fruitcake/laravel-cors (v2.2.0 => v3.0.0): Extracting archive
77 package suggestions were added by new dependencies, use `composer suggest` to see details.
Generating optimized autoload files
> IlluminateFoundationComposerScripts::postAutoloadDump
> @php artisan package:discover --ansi

In Finder.php line 588:

  syntax error, unexpected token ")"


Script @php artisan package:discover --ansi handling the post-autoload-dump event returned with error code 1

Вроде обновление закончилось, но что-то пошло не так и теперь в консоли выдает ошибку syntax error, unexpected token ")" на Finder.php:588.

Я проверил этот файл, и он выглядит правильно.

Когда я открываю свой проект в браузере, я получаю эту ошибку:

Fatal error: Uncaught RuntimeException: A facade root has not been set. in /var/www/html/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php:334
Stack trace:
#0 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/RegisterErrorViewPaths.php(18): IlluminateSupportFacadesFacade::__callStatic('replaceNamespac...', Array)
#1 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php(626): IlluminateFoundationExceptionsRegisterErrorViewPaths->__invoke()
#2 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php(607): IlluminateFoundationExceptionsHandler->registerErrorViewPaths()
#3 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php(538): IlluminateFoundationExceptionsHandler->renderHttpException(Object(SymfonyComponentHttpKernelExceptionHttpException))
#4 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php(444): IlluminateFoundationExceptionsHandler->prepareResponse(Object(IlluminateHttpRequest), Object(SymfonyComponentHttpKernelExceptionHttpException))
#5 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php(364): IlluminateFoundationExceptionsHandler->renderExceptionResponse(Object(IlluminateHttpRequest), Object(ParseError))
#6 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(427): IlluminateFoundationExceptionsHandler->render(Object(IlluminateHttpRequest), Object(ParseError))
#7 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(115): IlluminateFoundationHttpKernel->renderException(Object(IlluminateHttpRequest), Object(ParseError))
#8 /var/www/html/public/index.php(52): IlluminateFoundationHttpKernel->handle(Object(IlluminateHttpRequest))
#9 {main}
  thrown in /var/www/html/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php on line 334

Я очистил все кеши в bootstrap/cahce/, а также в папках storage/framework/cache/data/, storage/framework/sessions/, storage/framework/views/.

Я использую PHP версии 8.0.16.

Композитор версии 2.0.12 01.04.2021 10:14:59.

Есть идеи, как это исправить?

Чтобы продолжить использование php 8.0, добавьте эти записи в ваш composer.json.

    "require": {
        ...
        "symfony/console": "6.0.*",
        "symfony/error-handler": "6.0.*",
        "symfony/finder": "6.0.*",
        "symfony/http-foundation": "6.0.*",
        "symfony/http-kernel": "6.0.*",
        "symfony/mailer": "6.0.*",
        "symfony/mime": "6.0.*",
        "symfony/process": "6.0.*",
        "symfony/routing": "6.0.*",
        "symfony/var-dumper": "6.0.*",
        "symfony/event-dispatcher": "6.0.*",
        "symfony/string": "6.0.*",
        "symfony/translation": "6.0.*",
        "symfony/translation-contracts": "3.0.*",
        "symfony/service-contracts": "3.0.*",
        "symfony/event-dispatcher-contracts": "3.0.*",
        "symfony/deprecation-contracts": "3.0.*",
        ...
    }

У меня работало с php 8.0 и Laravel 9.


8

Philvv
2 Июн 2022 в 15:48

Я сделал :

composer require --ignore-platform-reqs symfony/finder 6.1

И у меня сейчас похожая проблема:

[2022-05-30 17:52:03] laravel.ERROR: syntax error, unexpected token ")" {"exception":"[object] (ParseError(code: 0): syntax error, unexpected token ")" at /vendor/symfony/finder/Finder.php:588)
[stacktrace]
#0 /vendor/composer/ClassLoader.php(346): Composer\Autoload\includeFile()
#1 /vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/LoadConfiguration.php(88): Composer\Autoload\ClassLoader->loadClass()
#2 /vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/LoadConfiguration.php(65): Illuminate\Foundation\Bootstrap\LoadConfiguration->getConfigurationFiles()
#3 /vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/LoadConfiguration.php(39): Illuminate\Foundation\Bootstrap\LoadConfiguration->loadConfigurationFiles()
#4 /vendor/laravel/framework/src/Illuminate/Foundation/Application.php(239): Illuminate\Foundation\Bootstrap\LoadConfiguration->bootstrap()
#5 /vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(310): Illuminate\Foundation\Application->bootstrapWith()
#6 /vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(127): Illuminate\Foundation\Console\Kernel->bootstrap()
#7 /artisan(37): Illuminate\Foundation\Console\Kernel->handle()
#8 {main}
"}

Так что я думаю, что это версия symfony/finder, которая несовместима с php 8.0, попробуйте понизить любой пакет, связанный с symfony, до 6.0.x, потому что я не думаю, что вам нужен symfony/finder напрямую, но какой-то другой пакет, такой как symfony/ http-клиент

Я думаю, что вы, возможно, в какой-то момент установили зависимости, используя php 8.1, и у вас есть неправильные версии пакетов, или, возможно, у вас установлен laravel 10, а не laravel 9?


2

Lk77
30 Май 2022 в 18:59

Обновление версии PHP до PHP 8.1 должно решить проблему. И обязательно снова запустите composer install или composer update.


0

Jesus Erwin Suarez
4 Июл 2022 в 11:45

Introduction

A common issue that I see when working with front-end JavaScript heavy apps is the dreaded “SyntaxError Unexpected Token in JSON” error! Now this error can be of the form:

SyntaxError: Unexpected token < in JSON at position 0

SyntaxError: Unexpected end of JSON input

syntaxerror: unexpected token '<', "<!doctype "... is not valid json

The error “SyntaxError Unexpected Token in JSON” appears when you try to parse content (for example — data from a database, api, etc), but the content itself is not JSON (could be XML, HTML, CSV) or invalid JSON containing unescaped characters, missing commas and brackets.

There are a few things you can try to fix this error:

  1. Check that the content you are trying to parse is JSON format and not HTML or XML

  2. Verify that there are no missing or extra commas.

  3. Make sure to check for unescaped special characters.

  4. Check for mismatched brackets or quotes.

  5. Make sure the JSON is valid. You can use a tool like JSONLint to validate your JSON and check for any errors.

1. Check that the content you are trying to parse is JSON format and not HTML or XML

A common reason why the error “SyntaxError Unexpected Token in JSON” comes up is that we are trying to parse content that is not even JSON.

Consider the following front-end JavaScript code:

  

fetch('https://localhost:3000/data')
  .then(response => response.json())
  .then(data => {
    console.log(data);
    // Use the data here
  })

In the above example, the fetch() function is being used to retrieve data from a API that returns JSON format — in this case https://localhost:3000/data.

The fetch() function then returns a promise, and when that promise resolves, we handle that with the response.json() method. This just takes our JSON response and converts it to a JSON object to be used!

After that we just console.log out the data object

Now for the server-side of things, look on to our Node JS route that returns the JSON /data

  

var http = require('http');

var app = http.createServer(function(req,res){
    res.setHeader('Content-Type', 'text/html');  Not returning JSON.
    res.end(JSON.stringify({ a: 1 }));
});
app.listen(3000);

We can see that it is setting the Header as text/html. This will give you the error:

syntaxerror: unexpected token '<', "<!doctype "... is not valid json

This is because we are trying to parse the content with JSON.parse() or in our case response.json() and receiving a HTML file!

To fix this, we just need to change the returned header to res.setHeader('Content-Type', 'application/json'):

  

...
var app = http.createServer(function(req,res){
    res.setHeader('Content-Type', 'application/json'); ✔️ Returning JSON.
    res.end(JSON.stringify({ a: 1 }));
});
...

Whats Content-Type request header anyway?

Pretty much every resource on the internet will need to have a type (similar to how your file system contains file types like images, videos, text, etc).
This is known as a MIME type (Multipurpose Internet Mail Extension)

Browsers need to know what content type a resource is so that it can best handle it. Most modern browsers are becoming good at figuring out which content type a resource is, but its not always 100% correct.

That is why still need to explicitly specify our request header content-type!

syntaxerror: unexpected token ‘<’, “<!doctype “… is not valid json

This error also comes up when your API is returning invalid error pages such as 404/500 HTML pages. Since HTML usually starts with a “less than” tag symbol (<) and JSON is not valid with < tags, it will through this error.

For example, when everything is working find, your node API will happily return JSON. However when it fails with a 500 internal error, it could return a custom HTML error page!
In this case, when you try to do JSON.parse(data) you will get the syntaxerror: unexpected token '<', "<!doctype "... is not valid json.

Additionally, check that you are calling the correct API url. As an example, lets say the API that returns JSON is using the /data route. If you misspelt this, you could be redirected to a 404 HTML page instead!

Tip: Use appropriate error handlers for non-JSON data

If you are using fetch() to retrieve your data, we can add a catch handler to give meaningful error messages to the user:

  

fetch('https://localhost:3000/data')
  .then(response => response.json())
  .then(data => {
    console.log(data);
    // Use the data here
  })
  .catch(error => console.error(error)); /*✔️ Friendly error message for debugging! */

If you are using JSON.parse() we can do this in a try/catch block as follows:

  

try {
    JSON.parse(data);
}
catch (error) {
    console.log('Error parsing JSON:', error, data); /*✔️ Friendly message for debugging ! */
}

JSON objects and arrays should have a comma between each item, except for the last one.

  

{
    "name": "John Smith"
    "age": 30
    "address": {
        "street": "123 Main St"
        "city": "Anytown"
        "state": "USA"
    }
}

This JSON object will throw a “syntaxerror unexpected token” error because there is no comma between “John Smith” and “age”, and also between “Anytown” and “state”.

To fix this, you would add commas as follows:

  

{
    "name": "John Smith",
    "age": 30,
    "address": {
        "street": "123 Main St",
        "city": "Anytown",
        "state": "USA"
    }
}

By adding commas between each item except for the last one, the JSON object is now in the correct format and should parse without error.

3. Make sure to use double quotes and escape special characters.

JSON strings must be wrapped in double quotes, and any special characters within the string must be properly escaped. Consider the following example:

  

{
    "name": "John Smith",
    "age": 30,
    "address": {
        "street": "123 Main St",
        "city": "Anytown",
        "state": "USA"
    },
    "message": "It's a lovely day"
}

When we try to parse this with JSON.parse, we will get the error: SyntaxError: Invalid or unexpected token.

The problem is with the following line using a apostrophe:

"message": "It's a lovely day"

  

{
    "name": "John Smith",
    "age": 30,
    "address": {
        "street": "123 Main St",
        "city": "Anytown",
        "state": "USA"
    },
    "message": "It's a lovely day"
}

As we can see, this will fix our error since we escape the aspostrophe as such:

"message": "It's a lovely day"

4. Check for mismatched brackets or quotes.

Make sure all brackets and quotes are properly closed and match up.

  

{
    "name": "John Smith",
    "age": 30,
    "address": {
        "street": "123 Main St",
        "city": "Anytown",
        "state": "USA"
    }

In this example, the JSON object is missing a closing curly bracket, which indicates the end of the object. Because of this, it will throw a “syntaxerror unexpected token” error.

To fix this, you would add the missing closing curly bracket as follows:

  

{
    "name": "John Smith",
    "age": 30,
    "address": {
        "street": "123 Main St",
        "city": "Anytown",
        "state": "USA"
    }
}

If you want to be sure that the JSON is valid, we can try to use the NPM package JSONLint (https://github.com/zaach/jsonlint)

We can install jsonlint with npm as follows:

  1. Open up the terminal
  2. Run NPM install npm install jsonlint -g
  3. We can then validate a file like so: jsonlint myfile.json

Summary

In this article I went over the SyntaxError: Unexpected token < in JSON at position 0 when dealing with parsing JSON with fetch or JSON.parse. This error is mainly due to the JSON not being in correct format or the content that we are trying to parse is not even JSON.

In the case of JSON being invalid, make sure to check for unescaped characters, missing commas, non-matching brackets and quotes.

To be really sure, check the JSON with tools like JSONLint to validate!

In the case of the content you are trying to parse being non-JSON such as HTML, check your API to make sure that error pages return JSON correctly instead of HTML pages.

Понравилась статья? Поделить с друзьями:
  • Syntax error unexpected token joomla
  • Syntax error invalid syntax python ошибка
  • Syntax error invalid syntax python pip
  • Syntax error unexpected token in json at position 0 opencart
  • Syntax error invalid syntax perhaps you forgot a comma