POST请求失败报错:预检请求无可用响应内容,求排查
POST请求报错“Failed to load response data: No content available for preflight request”解决方法
核心问题:请求头拼写错误
前端代码里的请求头键名写错了——Content-Tpye应该是Content-Type。这个拼写错误会让浏览器无法正确标识请求的内容格式,导致后端无法解析JSON请求体,最终引发预检请求(OPTIONS)无响应数据的报错。
修正后的前端代码
//Fetch request to create a movie createMovieButton.addEventListener('click', () => { const movie = {name: 'Movie 100', genre: 'Action'} fetch('http://localhost:8080/movies', { method: 'POST', headers: { // 修正拼写错误:Tpye → Type 'Content-Type': 'application/json' }, body: JSON.stringify(movie) }).then(response => response.json()) .then(result => console.log(result)) }) //Fetching the data from the backend async function getMovies() { const response = await fetch('http://localhost:8080/movies') const movies = await response.json() console.log(movies) } getMovies()
额外验证项
- 后端的
express.json()中间件已经正确配置,负责解析JSON请求体,这部分没问题。 - 全局启用的
cors中间件配置正确,默认允许所有跨域请求,无需额外调整。 - 修改代码后重启服务器,确保新代码生效。
内容的提问来源于stack exchange,提问作者Dylan Guidry
相关产品推荐
相关产品推荐

