发送 DELETE 请求时的 CORS 响应

CORS response when sending a DELETE request

我正在尝试向我的后端服务器发送一个 DELETE 请求,但我一直将此响应打印到我的控制台:

Response {type: 'cors', url: 'http://localhost:3003/delete', redirected: false, status: 200, ok: true, …}
body: (...)
bodyUsed: false
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: "OK"
type: "cors"
url: "http://localhost:3003/delete"
[[Prototype]]: Response

我不知道为什么会这样。

server.js

const express = require('express')
const knex = require('knex')
const cors = require('cors')



const db = knex({
    client: 'pg',
    connection: {
        host: '127.0.0.1',
        user: 'postgres',
        password: 'psql',
        database: 'blogspot',
        port: 5432
    }
});

const app = express();

app.use(express.json())
app.use(cors())


// Delete Blog
app.delete('/delete', (req, res) => {
    const {id} = req.body;
    db.select('*').from('blogs')
    .where({
        id: id
    })
    .del()
    .then(() => {
        res.json('Deleted Successfully')
    })
    .catch(err => res.status(404).json('An error occured'))
})

fetchAPI.js

function deleteBlog (blog) {
        fetch('http://localhost:3003/delete', {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(blog)
        }).then(resp => {
            console.log(resp)
            if (resp === 'Deleted Successfully') {
                navigate(0)
            } else if (resp === 'An error occured') {
                console.log('Something went wrong')
            } else {
                console.log('ERROR')
            }
           
        })
    }

我不断将 'ERROR' 连同上面粘贴的 cors 响应打印到我的控制台。当我刷新时,我发现博客已被删除,但响应肯定是一个错误,因为 navigate(0) 不是 运行 并且 ERROR 被打印到我的控制台。我尝试删除 'Content-Type': 'application/json' header 并将 id 作为请求参数发送,但我遇到了同样的错误。

响应类型为“cors”的事实仅意味着某些内容已按 CORS 策略过滤(请参阅 https://developer.mozilla.org/en-US/docs/Web/API/Response/type),但您没有收到任何错误代码,statusCode 为 200。

由于您的响应内容类型是 JSON,您还必须在读取响应之前解析 json 解析:

function deleteBlog(blog) {
  fetch('http://localhost:3003/delete', {
      method: 'DELETE',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(blog)
    })
    .then(data => data.json())
    .then(resp => {
      // I also suppose that you will more likely find 
      // your "Deleted successfully" in the resp.body property, so :
      if (resp.body === 'Deleted Successfully') {
        navigate(0)
      } else if (resp.body === 'An error occured') {
        console.log('Something went wrong')
      } else {
        console.log('ERROR')
      }
    })
}