// server.js
app.post('/api/user/hello', (req, res) => {
res.setHeader('Access-Control-Allow-Origin', '*')
// 权限设置(如果有个多,用 ,隔开),暴露给前端
res.setHeader('Access-Control-expose-Headers', 'myHeader')
// 后端自定义响应头
res.set('myHeader', 123)
res.json({ hello: 'world' })
})
// index.html
fetch('http://localhost:3000/api/user/hello', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
}).then(res => {
// 前端获取自定义响应头(前提:后端需要加一个权限)
console.log(res.headers.get('myHeader'))
return res.json()
}).then(response => {
})
需要满足以下条件:
'Content-Type'为 'application/json'。fetch('http://localhost:3000/list', {
method: 'POST',
headers:{
'Content-Type':'application/json'
},
body: JSON.stringify({"name": "add"})
})
.then(res=> {
res.json()
})
.then(data=>{
console.log(data)
})


app.use('*', (req, res, next) => {
//此时后端为 localhost:3000 如果设为 * 则都可以请求,但是不能种 session
//Access-Control-Allow-Origin 默认只支持 get post head
res.setHeader('Access-Control-Allow-Origin', 'http://127.0.0.1:3000')
res.setHeader('Access-Control-Allow-Methods', 'GET,POST,HEAD,PATCH,DELETE,PUT')
//支持application/json
res.setHeader('Access-Control-Allow-Headers', 'Content-Type')
next()
})