发送DELETE请求时的CORS响应



我正试图向后端服务器发送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"标头,并将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')
}
})
}

最新更新