“未捕获(承诺中)语法错误:输入意外结束”使用从 Chrome 获取
目标:从 Express JS 向浏览器请求提供一些基本数据,所有这些数据都在本地主机上本地运行。
当我直接使用浏览器连接到 URL (http://localhost/test) 时,我会在浏览器窗口中看到我尝试接收的数据。但是,当我在 HTML 文档的标记中执行以下代码时,我收到“未捕获(承诺中)语法错误:意外的输入结束”并且未检索到任何数据。
fetch('http://localhost/test', {
'content-type': 'application/json',
mode: 'no-cors',
method: 'GET',
redirect: 'follow'
})
.then(response => response.json())
.then(json => console.log(json))
这是我的 Express 代码:
app.get("/test", (req, res) => {
res.header(
"Access-Control-Allow-Origin","http://localhost:*"
)
res.json( {username: 'Joe'})
});
我开始时没有上面的“res.header”,但经过多次搜索后发现这是一个建议。 CURL 和 XMLHttpRequest 都工作正常。
Objective: provide some basic data from Express JS to browser requests, all running locally on localhost.
When I connect to the URL (http://localhost/test) with the browser directly I see the data I'm trying to receive in the browser window. However, when I execute the following code in a tag in an HTML document I get "Uncaught (in promise) SyntaxError: Unexpected end of input" and no data retrieved.
fetch('http://localhost/test', {
'content-type': 'application/json',
mode: 'no-cors',
method: 'GET',
redirect: 'follow'
})
.then(response => response.json())
.then(json => console.log(json))
Here's my Express code:
app.get("/test", (req, res) => {
res.header(
"Access-Control-Allow-Origin","http://localhost:*"
)
res.json( {username: 'Joe'})
});
I started without the "res.header" above but after many searches found that as a suggestion. CURL and XMLHttpRequest both work fine.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我最近看到一些相关的东西。我认为问题可能是您使用的是
no-cors
模式,该模式需要不透明的响应。我不是这方面的专家,但我建议您检查我分享的链接。我在普通 JS 和在 Azure(函数应用程序)上运行的 REST API 中遇到了类似的问题。在我的 JS 代码中,我删除了请求的
no-cors
模式;在提供响应的 REST API 中,我将允许的来源更改为*
通配符。希望它有任何帮助。I've seen something somewhat related recently. I think the problem might be that you are using a
no-cors
mode, which expects an opaque response. I'm no specialist in the matter but I suggest you check the link I shared.I had a similar issue in vanilla JS and a REST API running on Azure (Function App). In my JS code, I removed the
no-cors
mode for the request; and in the REST API providing the response, I changed the allowed origins to*
wildcard. Hope it's of any help.