【问题标题】:How to get localhost server to return JSON instead of HTML in node.js如何让 localhost 服务器在 node.js 中返回 JSON 而不是 HTML
【发布时间】:2021-01-21 00:51:15
【问题描述】:

我收到以下错误:

SyntaxError: Unexpected token

我了解服务器正在返回 HTML,而客户端需要解析的 JSON。我正在使用本地主机服务器。如何让 localhost 服务器返回 JSON 而不是 HTML?

下面是我的代码:

// required modules
const https = require('https');

// json files link
const mimeURL = 'https://gist.github.com/AshHeskes/6038140#file-file-extension-to-mime-types-json';

const getMimeType = extension => {
    return new Promise((resolve, reject) => {
        https.get(mimeURL, response => {
            if(response.statusCode < 200 || response.statusCode > 299) {
                reject(`Error: Fail to load mime types json file: ${response.statusCode}`);
                console.log(`Error: Fail to load mime types json file: ${response.statusCode}`);
                return false;
            }

        let data = '';
        // receive data by chunks
    response.on('data', chunk => {
        data += chunk;
  });
//   once you received all chunks of data
      response.on('end', () => {
        resolve(JSON.parse(data)[extension]);
        });

    }).on('error', (e) => {
        console.error(e);
    });
});

};
module.exports = getMimeType;

【问题讨论】:

  • 欢迎来到 Stack Overflow。请注意,在这里说“谢谢”的首选方式是投票赞成好的问题和有用的答案(一旦你有足够的声誉这样做),并接受对你提出的任何问题最有帮助的答案(这也给出了你的声誉小幅提升)。请参阅About 页面和How do I ask questions here?

标签: node.js json


【解决方案1】:

您请求的 URL 不是 JSON,它是托管在 Github Gist 上的格式化元素。要获取原始 JSON,您需要单击 Gist 标题旁边的原始按钮:

raw JSON URL 提出请求,它会起作用。

这是您特定案例的代码:

// required modules
const https = require('https');

// json files link
const mimeURL = 'https://gist.githubusercontent.com/AshHeskes/6038140/raw/27c8b1e28ce4c3aff0c0d8d3d7dbcb099a22c889/file-extension-to-mime-types.json';

const getMimeType = extension => {
    return new Promise((resolve, reject) => {
        https.get(mimeURL, response => {
            if(response.statusCode < 200 || response.statusCode > 299) {
                reject(`Error: Fail to load mime types json file: ${response.statusCode}`);
                console.log(`Error: Fail to load mime types json file: ${response.statusCode}`);
                return false;
            }

        let data = '';
        // receive data by chunks
    response.on('data', chunk => {
        data += chunk;
  });
//   once you received all chunks of data
      response.on('end', () => {
        resolve(JSON.parse(data)[extension]);
        });

    }).on('error', (e) => {
        console.error(e);
    });
});

};
module.exports = getMimeType;

【讨论】:

  • 您的回答解决了我的问题 - 谢谢!
  • 嗨@novycody,很高兴听到我能帮上忙!在这种情况下,您可以单击帖子顶部旁边的复选标记。这向这里的社区展示了这个答案解决了您的问题,并为您自己(和我自己)带来了一点声誉。谢谢!
  • 在我学会浏览这个超级有用的论坛时,我会这样做并感谢您的提示。
  • @novycody 很高兴听到这个消息!祝你有美好的一天。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多