Меню

Invalid shorthand property initializer ошибка js

I wrote the following code in JavaScript for a node project, but I ran into an error while testing a module. I’m not sure what the error means. Here’s my code:

var http = require('http');
// makes an http request
var makeRequest = function(message) {
 var options = {
  host: 'localhost',
  port = 8080,
  path : '/',
  method: 'POST'
 }
 // make request and execute function on recieveing response
 var request = http.request(options, function(response) {
  response.on('data', function(data) {
    console.log(data);
  });
 });
 request.write(message);
 request.end();
}
module.exports = makeRequest;

When I try to run this module, it throws the following error:

$ node make_request.js
/home/pallab/Desktop/make_request.js:8
    path = '/',
    ^^^^^^^^^^
SyntaxError: Invalid shorthand property initializer
    at Object.exports.runInThisContext (vm.js:76:16)
    at Module._compile (module.js:542:28)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:394:7)
    at startup (bootstrap_node.js:149:9)
    at bootstrap_node.js:509:3

I dont quite get what this means, and what I can do to resolve this.

asked Feb 2, 2017 at 15:47

Pallab Ganguly's user avatar

Pallab GangulyPallab Ganguly

2,9932 gold badges10 silver badges9 bronze badges

Because it’s an object, the way to assign value to its properties is using :.

Change the = to : to fix the error.

var options = {
  host: 'localhost',
  port: 8080,
  path: '/',
  method: 'POST'
 }

Tobias's user avatar

Tobias

4,9296 gold badges34 silver badges39 bronze badges

answered Feb 2, 2017 at 15:49

Diego Faria's user avatar

Diego FariaDiego Faria

8,6643 gold badges25 silver badges33 bronze badges

4

use : instead of using = sign for fixing the error.

answered Mar 22, 2021 at 5:12

Ashwani Kumar Kushwaha's user avatar

Change the = to : to fix the error.

var makeRequest = function(message) {<br>
 var options = {<br>
  host: 'localhost',<br>
  port : 8080,<br>
  path : '/',<br>
  method: 'POST'<br>
 }

Procrastinator's user avatar

answered Oct 22, 2020 at 5:37

amit paswan's user avatar

In options object you have used «=» sign to assign value to port but we have to use «:» to assign values to properties in object when using object literal to create an object i.e.»{}» ,these curly brackets. Even when you use function expression or create an object inside object you have to use «:» sign.
for e.g.:

    var rishabh = {
        class:"final year",
        roll:123,
        percent: function(marks1, marks2, marks3){
                      total = marks1 + marks2 + marks3;
                      this.percentage = total/3 }
                    };

john.percent(85,89,95);
console.log(rishabh.percentage);

here we have to use commas «,» after each property.
but you can use another style to create and initialize an object.

var john = new Object():
john.father = "raja";  //1st way to assign using dot operator
john["mother"] = "rani";// 2nd way to assign using brackets and key must be string

answered Mar 3, 2019 at 15:49

r.jain's user avatar

Use : instead of =

see the example below that gives an error

app.post('/mews', (req, res) => {
if (isValidMew(req.body)) {
    // insert into db
    const mew = {
        name = filter.clean(req.body.name.toString()),
        content = filter.clean(req.body.content.toString()),
        created: new Date()
    };

That gives Syntex Error: invalid shorthand proprty initializer.

Then i replace = with : that’s solve this error.

app.post('/mews', (req, res) => {
if (isValidMew(req.body)) {
    // insert into db
    const mew = {
        name: filter.clean(req.body.name.toString()),
        content: filter.clean(req.body.content.toString()),
        created: new Date()
    };

answered Dec 24, 2019 at 17:36

akshay_sushir's user avatar

I’m trying to validate a pin using the following function

function validate(num){
  num.length === 4 || num.length === 6 ? {
    regex = /d+/,
    regex:test(num)
  } 
  :
  false
}

however I’m getting this error and I can’t figure out why

    /home/runner/index.js:3
    regex = /d+/,
    ^^^^^^^^^^^^^

SyntaxError: Invalid shorthand property initializer

Barmar's user avatar

Barmar

716k53 gold badges481 silver badges597 bronze badges

asked Dec 20, 2019 at 23:12

Fredrick Barrett's user avatar

Fredrick BarrettFredrick Barrett

3,0812 gold badges6 silver badges6 bronze badges

5

As others have pointed out, you can’t put statements in conditional expressions (or any other expression, either), you can only put expressions.

The error you’re getting is because it thinks you’re trying to write an object literal, but you can’t have assignments inside object literals.

You can use a normal if statement:

if (num.length == 4 || num.length == 6) {
    var regex = /d+/;
    return regex.test(num);
} else {
    return false;
}

But there’s no need for the conditional at all, you can test the length in the regexp itself.

function validate(num) {
    return /^d{4}$|^d{6}$/.test(num);
}

answered Dec 20, 2019 at 23:24

Barmar's user avatar

While I cannot recommend such here, it is important to keep in mind that a function expression can be used in an expression context. This is done all the time, such as for callbacks, and the same concept is transferable elsewhere..

Here is a minimal conversion of the original (which maintains as many of the original’s bugs and other features, except where they caused parse errors) showing a function expression. This specific case is also called an «IIFE».

function validate(num){
  return num.length === 4 || num.length === 6
   ? (function() {
       let regex = /d+/; 
       return regex.test(num);
     })()
   : false;
} 

answered Dec 20, 2019 at 23:51

user2864740's user avatar

user2864740user2864740

58.8k14 gold badges137 silver badges211 bronze badges

You cannot use the ?: operator with statements; only expressions.

However, there is no need to define a variable for your regex here. You can just call .test on the regex literal directly:

function validate(num){
  return num.length === 4 || num.length === 6 ? /d+/.test(num) : false
}

Even better, just use the && operator, which is logically equivalent here:

function validate(num){
  return (num.length === 4 || num.length === 6) && /d+/.test(num);
}

answered Dec 20, 2019 at 23:22

kaya3's user avatar

kaya3kaya3

45.1k4 gold badges58 silver badges88 bronze badges

0

I’m trying to validate a pin using the following function

function validate(num){
  num.length === 4 || num.length === 6 ? {
    regex = /d+/,
    regex:test(num)
  } 
  :
  false
}

however I’m getting this error and I can’t figure out why

    /home/runner/index.js:3
    regex = /d+/,
    ^^^^^^^^^^^^^

SyntaxError: Invalid shorthand property initializer

Barmar's user avatar

Barmar

716k53 gold badges481 silver badges597 bronze badges

asked Dec 20, 2019 at 23:12

Fredrick Barrett's user avatar

Fredrick BarrettFredrick Barrett

3,0812 gold badges6 silver badges6 bronze badges

5

As others have pointed out, you can’t put statements in conditional expressions (or any other expression, either), you can only put expressions.

The error you’re getting is because it thinks you’re trying to write an object literal, but you can’t have assignments inside object literals.

You can use a normal if statement:

if (num.length == 4 || num.length == 6) {
    var regex = /d+/;
    return regex.test(num);
} else {
    return false;
}

But there’s no need for the conditional at all, you can test the length in the regexp itself.

function validate(num) {
    return /^d{4}$|^d{6}$/.test(num);
}

answered Dec 20, 2019 at 23:24

Barmar's user avatar

While I cannot recommend such here, it is important to keep in mind that a function expression can be used in an expression context. This is done all the time, such as for callbacks, and the same concept is transferable elsewhere..

Here is a minimal conversion of the original (which maintains as many of the original’s bugs and other features, except where they caused parse errors) showing a function expression. This specific case is also called an «IIFE».

function validate(num){
  return num.length === 4 || num.length === 6
   ? (function() {
       let regex = /d+/; 
       return regex.test(num);
     })()
   : false;
} 

answered Dec 20, 2019 at 23:51

user2864740's user avatar

user2864740user2864740

58.8k14 gold badges137 silver badges211 bronze badges

You cannot use the ?: operator with statements; only expressions.

However, there is no need to define a variable for your regex here. You can just call .test on the regex literal directly:

function validate(num){
  return num.length === 4 || num.length === 6 ? /d+/.test(num) : false
}

Even better, just use the && operator, which is logically equivalent here:

function validate(num){
  return (num.length === 4 || num.length === 6) && /d+/.test(num);
}

answered Dec 20, 2019 at 23:22

kaya3's user avatar

kaya3kaya3

45.1k4 gold badges58 silver badges88 bronze badges

0

Any site I visit in Chrome today, including Google.com, shows the following error in the console.log:

Uncaught SyntaxError: Invalid shorthand property initializer

The source shows as (unknown).
I wonder if I have a bad extension or something.
I’d rather not reset Chrome.
Are there any other troubleshooting tips?

asked Aug 10, 2017 at 22:37

Shawn's user avatar

This is caused by a recent chrome update. Somewhere in the chrome JSVM code they use a «=» where a «:» should be used to assign a value to an object’s property:

enter image description here

I think we have to wait for a patch or downgrade chrome.

EDIT: It seems to be something caused by the chrome developer tools:
https://stackoverflow.com/questions/17367560/chrome-development-tool-vm-file-from-javascript

Altough searching the dev tools code does not give any match either.

EDIT2: The answer of user gotoken seems to resolve the issue.

enter image description here

EDIT3: Seems that the solution of user gotoken is not a permanent one. Error reappears after some time. BetterHistory Extension needs to be patched.

answered Aug 11, 2017 at 7:31

Lucian Depold's user avatar

3

The answers are correct. However, I thought maybe a simple process answer would be helpful:

  1. In the address bar enter: chrome://extensions (Press enter to display your extensions.)
  2. The tab label should be «Extensions» and a list of your installed extensions should be on that page.
  3. Look for Better History. Should be near the top if your extensions are ordered by name.
  4. Click on the Enabled checkbox (the check mark should clear).
  5. Click on the Enabled checkbox again and the check mark should reappear.

That’s it. You will probably have to refresh the tab where you’re getting the error.

If this was too simple then please let me know.

Further. I found that this didn’t solve the problem once and for all. I’m using Vue and Webpack and found that the error eventually (generally after a few restarts) returns. Reset the enabled checkbox again and it goes away again. I guess we’re just going to have to live with it until the bug is fixed!

answered Aug 22, 2017 at 15:06

PhilMDev's user avatar

1

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Invalid procedure call or argument vba ошибка
  • Invalid outside procedure ошибка