简体   繁体   English

parameter.json() 上的输入意外结束

[英]Unexpected end of input on parameter.json()

I'm learning about servers and APIs , I do not know too much about how data is received and sended through requests.我正在学习服务器和API ,我不太了解如何通过请求接收和发送数据。 So i got my server with Node.js using Mongoose and Express.js :所以我使用MongooseExpress.js获得了带有Node.js 的服务器:

server.get('/api/items', async (req, res)=>{
    let results = await TvModel.find({model: 4013});
    res.json(results);
});

So if i send the get request via postman i get this:因此,如果我通过邮递员发送获取请求,我会得到:

[
    {
        "_id": "60f62a33a1dbf8031088cd3b",
        "name": "Sony",
        "model": "4013",
        "size": 8,
        "idSerial": 1,
        "__v": 0
    }
]

So, trying to get the data via JavaScript using fetch api:因此,尝试使用 fetch api 通过 JavaScript 获取数据:

fetch(API_URL, {mode: 'no-cors'})
    .then((resolve) => {resolve.json()})

When executing this code, i get an error on the console:执行此代码时,我在控制台上收到错误消息:

Uncaught (in promise) SyntaxError: Unexpected end of input

What is the SyntaxError i cannot see?我看不到的 SyntaxError 是什么?

I solved it myself by doing the following:我通过执行以下操作自己解决了这个问题:

Thanks to @Bravo 's answer, I was able to get an idea of what my error was:感谢@Bravo的回答,我能够了解我的错误是什么:

"did you add that header due to a CORS error perhaps thinking this will bypass CORS? " “您是否由于CORS错误添加了该标头,可能认为这会绕过CORS?

Since I am using express.js for my server, I had to install a middleware for my server, an npm module called "cors" .由于我在我的服务器上使用express.js ,我必须为我的服务器安装一个中间件,一个名为"cors"的 npm 模块。

So the only thing i needed to add was this line of code:所以我唯一需要添加的是这行代码:

const cors = require('cors');

app = express();
app.use(cors());

Anyway you can read more of this on official documentation of cors in the official express.js website无论如何,您可以在官方 express.js 网站上的 cors官方文档中阅读更多内容

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM