【问题标题】:Uncaught (in promise) SyntaxError: Unexpected end of input with JS [duplicate]未捕获(承诺)SyntaxError:JS输入意外结束[重复]
【发布时间】:2019-10-24 03:38:12
【问题描述】:

在我的客户端,我只是想提醒我从服务器获得的响应。

function displayItems()
{
    fetch('http://ip_address:3000/users',{
        method:'POST',
        headers:{
            'Accept':'application/json',
            'Content-Type':'application/json',
        },
        mode:'no-cors'
    })
    .then((response) => {return response.json();})
    .then((res) => { alert(res.message)})
}

在我的服务器端,我有这个简单的代码来响应请求

var express = require('express');
var router = express.Router();

/* GET users listing. */
router.post('/', function(req, res, next) {

  let obj = {message:'fsdfsdfsdfsd'}
  res.send(obj);

  console.log('server Reached')
});

module.exports = router;

查找其他相关问题后,我仍然无法解决这个错误:Uncaught (in promise) SyntaxError: Unexpected end of input.

提前感谢那些看这篇文章的人。

【问题讨论】:

    标签: javascript node.js express


    【解决方案1】:

    除了 Quentin 指出的重复的no-cors 问题(他回答here),还有其他几个问题:

    您发送的不是 JSON:

    res.send('Hello world'); // <=== This is plain text
    

    ...所以response.json() 在尝试解析响应时会失败。

    如果你只是发送这样的文本,你会使用response.text()而不是.json()来阅读它。

    您也没有正确检查 HTTP 错误。不仅仅是你,几乎每个人都会犯这个错误(我有written up here),这是fetch API 中的一个缺陷(恕我直言)。要正确检查错误并接收文本(而不是 JSON),请参阅*** cmets:

    function displayItems()
    {
        fetch('http://172.30.117.7:3000/users',{
            method:'POST',
            headers:{
                'Accept':'application/json',
                'Content-Type':'application/json',
            },
            mode:'no-cors'
        })
        .then((response) => {
            // *** Check for HTTP failure
            if (!response.ok) {
                throw new Error("HTTP status " + response.status);
            }
            // *** Read the text of the response
            return response.text();
        })
        .then((message) => {
            // *** Use the text
            alert(message);
        })
        .catch((error) => {
            /* ...*** handle/report error, since this code doesn't return the promise chain...*/
        });
    }
    

    或者,如果您愿意,您可以发回 JSON:

    response.json({message: "Hi there"});
    

    ...然后在客户端上:

    function displayItems()
    {
        fetch('http://172.30.117.7:3000/users',{
            method:'POST',
            headers:{
                'Accept':'application/json',
                'Content-Type':'application/json',
            },
            mode:'no-cors'
        })
        .then((response) => {
            // *** Check for HTTP failure
            if (!response.ok) {
                throw new Error("HTTP status " + response.status);
            }
            // *** Read and parse the JSON
            return response.json();
        })
        .then((res) => {
            // *** Use the object
            alert(res.message);
        })
        .catch((error) => {
            /* ...*** handle/report error, since this code doesn't return the promise chain...*/
        });
    }
    

    但是再次,所有这些都不是昆汀指出的主要问题。

    【讨论】:

    • 如果Hello World 是问题所在,它会抱怨H 是无效的JSON。由于 no-cors 模式,内容意外结束而失败。
    • @Quentin - 谢谢,我猜错误会有所不同,不是吗?以上所有内容仍然适用,因此我已将其标记为 CW 并指出这些是单独的,其他问题。再次感谢!
    • 那是我的愚蠢。我修改了我的代码。本质上我并试图打印对象的键值对。
    • @Quentin 很抱歉第一个代码,我最初想将对象作为消息发送。我添加了检查并将“no-cors”更改为“cors”。我现在收到此错误'来自原点'null'已被CORS策略阻止:对预检请求的响应未通过访问控制检查:请求的资源上不存在'Access-Control-Allow-Origin'标头。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。如何使服务器允许使用 Access-Control-Allow-Origin 标头读取响应
    • @Quentin 添加了以下代码:app.use(function (req, res, next) { res.setHeader('Access-Control-Allow-Origin', '*'); res. setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content- type'); res.setHeader('Access-Control-Allow-Credentials', true); next(); });我仍然收到 CORS 政策错误。请帮帮我
    猜你喜欢
    • 2019-01-17
    • 2017-09-07
    • 1970-01-01
    • 2021-01-09
    • 2020-06-26
    • 1970-01-01
    • 1970-01-01
    • 2017-12-22
    • 2023-03-03
    相关资源
    最近更新 更多