无效的速记属性初始化程序


164

我使用JavaScript为节点项目编写了以下代码,但是在测试模块时遇到错误。我不确定错误是什么意思。这是我的代码:

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;

当我尝试运行此模块时,它将引发以下错误:

$ 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

我不太明白这意味着什么,以及我能做些什么来解决这个问题。

Answers:


439

由于它是一个对象,因此将值分配给其属性的方法是使用:

更改=,以:修复错误。

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

这工作,但我认为你用=来存储数字和:字符串
Pallab甘古利

1
请参阅对象初始化程序文档,以了解如何在javascript中初始化对象文字。特别是称为创建对象的会话。
Diego Faria

6
我以为您=用来存储数字和:字符串,我想知道您将从何处得到这个想法。

2
啊!是时候喝杯咖啡了。谢谢。:)
ArendE

5

当您尝试分配一个等于(=)符号而不是冒号(:)的对象时,通常会出现此错误

正确的代码应类似于:

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

3

在options对象中,您已经使用“ =”符号为端口分配了值,但是在使用对象文字创建对象(即“ {}”)时,我们必须使用“:”为对象中的属性分配值,这些大括号。即使使用函数表达式或在对象内部创建对象,也必须使用“:”符号。例如:

    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);

在这里,我们必须在每个属性后使用逗号“,”。但是您可以使用其他样式来创建和初始化对象。

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

1

使用:代替=

请参阅下面的示例,该示例给出了错误

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()
    };

这给出了Syntex错误:速记属性初始化无效。

然后我替换=:解决该错误。

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()
    };
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.