【问题标题】:SyntaxError: Unexpected identifier for "fetch"SyntaxError:“获取”的意外标识符
【发布时间】:2021-12-28 07:13:07
【问题描述】:

我正在使用 NodeJS 制作一个不和谐的机器人,每次我启动机器人时它都会显示这个错误:

headers = (await fetch(filtered.fileUrl, { method: 'HEAD' })).headers
                 ^^^^^
SyntaxError: Unexpected identifier

我所知道的是,fetch 需要节点获取。起初,我认为问题在于我使用的是 node-fetch@3.0.0,它不支持 const fetch = require('node-fetch'),但即使我将其降级为 node-fetch@2.6.1,这个确切的问题仍然存在。

完整代码:

const fetch = require('node-fetch')
const Booru = require('booru')
const Discord = require('discord.js')
const { escapeMarkdown } = Discord.Util
const path = require('path')
const Color = `RANDOM`;
    module.exports = {
      info: {
        name: "booru",
        description: "booru image scraper",
        cooldown: 30,
      },
      async execute(client, message, args, Discord) {
        const tag_query = args.join(' ');

        if (!message.content.includes('help')) {
          if (!message.content.includes('something')) {
            const hornyEmbed = new Discord.MessageEmbed()
              .setTitle('embed cut to preserve space')
            if (!message.channel.nsfw) return message.channel.send(hornyEmbed)

            Booru.search('gelbooru', tag_query, {
                limit: 1,
                random: true
              })
              .then(posts => {
                const filtered = posts.blacklist(['blacklist, of course.'])
                if (filtered.length === 0) {
                  const notfoundEmbed = new Discord.MessageEmbed()
                    .setDescription("embed cut to preserve space")
                  message.channel.send(notfoundEmbed)
                }

                let tags =
                  filtered.tags.join(', ').length < 50 
                  ? Discord.Util.escapeMarkdown(filtered.tags.join(', ')) 
                  : Discord.Util.escapeMarkdown(filtered.tags.join(', ').substr(0, 50)) 
                  + `... [See All](https://giraffeduck.com/api/echo/?w=${Discord.Util
                                            .escapeMarkdown(filtered.tags.join(',').replace(/(%20)/g, '_'))
                                            .replace(/([()])/g, '\\$1')
                                            .substring(0, 1200)})`

                let headers
                let tooBig = false
                let imgError = false

                try {
                  headers = (await fetch(filtered.fileUrl, {
                    method: 'HEAD'
                  })).headers
                } catch (e) {
                  imgError = true
                }

                if (headers) {
                  tooBig = parseInt(headers.get('content-length'), 10) / 1000000 > 10
                }

                for (let post of posts) {

                  embed_nsfw = new Discord.MessageEmbed()
                    .setTitle('you horny')
                    .setColor('#FFC0CB')
                    .setAuthor('-')
                    .setDescription(`-` +
                      `**Provided by:** Gelbooru.com | `, +`[**Booru Page**](${filtered.postView}) | ` +
                      `**Rating:** ${filtered.rating.toUpperCase()} | ` +
                      `**File:** ${path.extname(filtered.file_url).toLowerCase()}, ${headers ? fileSizeSI(headers.get('content-length')) : '? kB'}\n` +
                      `**Tags:** ${tags}` +
                      (!['.jpg', '.jpeg', '.png', '.gif'].includes(
                          path.extname(filtered.fileURL).toLowerCase(),
                        ) ?
                        '`The file will probably not embed.`' :
                        '') +
                      (tooBig ? '\n`The image is over 10MB and will not embed.`' : '') +
                      (imgError ? '\n`I got an error while trying to get the image.`' : ''),
                    )
                    .setImage(filtered.sampleUrl)
                  message.channel.send(embed_nsfw);
                }
              })
          }
          if (message.content.includes('something')) {
            const helpEmbed = new Discord.MessageEmbed()
              .setTitle('cut to preserver space')
            message.channel.send(helpEmbed)
          }
        }
        if (message.content.includes('help')) {
          const helpEmbed = new Discord.MessageEmbed()
            .setTitle('cut to preserver space')
          message.channel.send(helpEmbed)
        }
      }
    }

我知道这段代码非常混乱,因为它基本上是由我找到的不同代码组合而成的科学怪人代码。因此,除了主要主题的解决方案之外,我还没有注意到另一个问题的指针也将不胜感激。

NodeJS 版本 16.13.0, NPM 版本 8.1.0, DiscordJS 版本 12.5.3, 在 Heroku 服务器上运行。

【问题讨论】:

    标签: javascript node.js fetch node-fetch


    【解决方案1】:

    尝试将async 添加到.then(posts =&gt; 。

    Booru.search('gelbooru', tag_query, {
    ...
      .then(async posts => {
        const filtered = posts.blacklist(['blacklist, of course.'])
        if (filtered.length === 0) {
          const notfoundEmbed = new Discord.MessageEmbed()
          .setDescription("embed cut to preserve space")
          message.channel.send(notfoundEmbed)
        }
    ...
    
      try {
        headers = (await fetch(filtered.fileUrl, {
          method: 'HEAD'
        })).headers
      } 
    

    【讨论】:

    • 谢谢,这解决了当前的问题。但是,在解决此问题后会出现另一个问题。它显示了这个错误; TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received undefined 错误可能发生在const embed_nsfw 上的.setDescription() 周围。知道我哪里出错了吗?
    • @dimactavish 这是完整的错误消息吗?根据我的经验,The "path" argument must be of type string. 发生在您将未定义的值传递给 path 模块的函数时。所以你可以检查filtered.file_url是否有值。
    • 感谢您的帮助,我才意识到应该是filtered.fileUrl 而不是filtered.file_url。
    猜你喜欢
    • 1970-01-01
    • 2020-10-12
    • 1970-01-01
    • 2013-09-19
    • 1970-01-01
    • 1970-01-01
    • 2017-10-11
    • 1970-01-01
    相关资源
    最近更新 更多