【问题标题】:using fetch with express and ejs gives 400 bad request aswell as unexpected token < in json将 fetch 与 express 和 ejs 一起使用会给出 400 个错误请求以及 json 中的意外令牌 <
【发布时间】:2021-09-11 14:36:19
【问题描述】:

使用 fetch 我收到一个错误的请求以及 JSON 中的意外令牌

获取请求:

const searchResults =  function(e){
fetch('/elpers/search' ,
{
 method: 'POST', 
 headers: {'Content-Type': 'application/json'},
 body: JSON.stringify(e.value)
}).then(res => {
  res.json()
}).then(data => {
 console.log(data)
}).catch(err => {
console.error(err)
})
}

发布路线

 const postSearch = (req, res) => {
console.log(req.body)
res.send({'result': 'value'});
}

编辑:这对我有用JSON.stringify({result: e.value})

错误:

search.js:2 POST http://localhost:3000/elpers/search 400 (Bad Request) VM118:1 Uncaught (in promise) SyntaxError: Unexpected token &lt; in JSON at position 0

【问题讨论】:

  • unexpected token &lt; 错误,根据我的经验,通常表明 API 调用在响应中导致了 JSON(通常是 HTML)以外的内容。这可能是因为 .then 正在被调用,它正在尝试执行 res.json()。当响应状态码为 400 时,Fetch 不会抛出错误。您应该找出导致 API 发出 400 Bad Request 的原因,并检查 .then 中的有效响应状态码。
  • 尝试删除 than() 。您正在使用 tww then 在函数中删除数据 then()。
  • @Matt U uh 我正在接收文本/htmt,即使我尝试发送 json 响应
  • 这能回答你的问题吗? Unexpected token < in JSON at position 0
  • @Jared Smith 我不知道如何应用已接受的答案我在 localhost 上运行服务器

标签: javascript node.js express ejs


【解决方案1】:

使用这个答案让我知道:

 const postSearch = (req, res) => {
     console.log(req.body)   // post if data is received here...
     res.json({
        message: "data received!",
        data: search,        // search should be the data that user fetched
    })
};

在客户端,只需 console.log 接收到的数据并查看它是否为 JSON :)))

编码愉快!

【讨论】:

  • 我认为 fetch 请求没有到达路由,因为它没有记录 req.body 错误是一样的
  • 如果你没有到达路线,你将不会收到任何东西,也许这就是问题所在。如果您使用的是 ExpressJS,请尝试从后端这样的简单路由。 app.post(/route, (req, res) =&gt; {console.log(req.body}; res.json({message: "data received!"}));
  • 不,它仍然没有到达路由,fetch 与 localhost 的工作方式不同吗?
  • 不行,试着把整个 localhost 放在请求 url 中。例如:“localhost:8080/elpers/search”。确保链接正确。
  • 不,即使在使用整个路由之前,post 路由确实尝试将其发送到localhost:3000/elpers/search
【解决方案2】:

您需要使用res.json() 而不是res.send()JSON.stringify(e.value)JSON.stringify({result: e.value})

【讨论】:

  • 这仍然给出相同的错误并且响应仍然是 text/html
  • postSearch 方法也应该是异步的。
  • 那么这应该意味着错误是从 JSON.stringify(e.value) e.value 触发的,否则它会抛出错误。
  • 我正在使用 html 输入来获取 e.value JSON.stringify 不能使其成为 JSON 吗?
  • 不,不是这样,使它成为 json 你可以做类似{ value: e.value} 的事情。 JSON.stringify 接受一个 json 并将其转换为字符串
猜你喜欢
  • 2019-06-06
  • 2016-11-24
  • 2022-06-21
  • 2016-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-05
相关资源
最近更新 更多