我用fetch请求参数,用get方法正常可以取到,用delete和post方法都不行

甜品屋 2020-04-14 02:34:50
## 这个是我的js文件

const express = require('express')
const app = express()
const bodyParser = require('body-parser')
app.use(express.static('public'))
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}))

app.all('*',function (req,res,next) {
res.header("Access-Control-Allow-Origin","*");
res.header("Access-Control-Allow-Methods","PUT, GET, POST, DELETE, OPTIONS");
res.header("Access-Control-Allow-Methods","X-Requested-With");
res.header("Access-Control-Allow-Methods","Content-Type");
next();
});
//fetch传统方式
app.get('/fetchdata',(req,res)=>{
res.send('传统方法获取参数'+req.query.id)
})
// fetch第二种方式
app.get('/fetchdata/:id',(req,res)=>{
res.send('2方法获取参数'+req.params.id)
})
app.delete('/fetchdata/:id',(req,res)=>{
res.send('delete方法获取参数'+req.params.id)
})
app.post('/fetchdata',(req,res)=>{
res.send('dpost方法获取参数'+req.body.username+'----------'+req.body.password)
})
app.get('/a1',(req,res)=>{
setTimeout(function(){
res.send('a1')
},1000);
})
app.get('/a2',(req,res)=>{
setTimeout(function(){
res.send('a2')
},2000);
})
app.get('/a3',(req,res)=>{
setTimeout(function(){
res.send('a3')
},3000);
})
app.get('/data',(req,res)=>{
res.send('Hello World')
})
app.get('/data1',(req,res)=>{
res.send('Hello tom')
})
app.get('/data2',(req,res)=>{
res.send('Hello jerry')
})
app.listen('3000',()=>{
console.log("running")
})


## 这个是我的html文件,用来请求js数据,用get方法可以成功


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="vue.js"></script>
<title>Document</title>
</head>
<body>
<script>
// fetch('http://localhost:3000/a1').then(function (data) {
// //这个必须的,用于获取后台对象
// return data.text();

// }).then(function (data) {
// console.log(data);
// })


// fetch传参
// fetch('http://localhost:3000/fetchdata?id=156', {
// method:'get'
// }).then(function (data) {
// return data.text();
// })
// .then(function (data) {
// console.log(data);
// })
//第二种方式(这里用get方法可以成功的)
// fetch('http://localhost:3000/fetchdata/456', {
// method:'get'
// }).then(function (data) {
// return data.text();
// })
// .then(function (data) {
// console.log(data);
// })
//这里用delete方法就失败了
fetch('http://localhost:3000/fetchdata/741', {
method: 'delete'
}).then(function (data) {
return data.text();
})
.then(function (data) {
console.log(data);
})
</script>
</body>
</html>

这个是报错的信息
Failed to load http://localhost:3000/fetchdata/741: Method DELETE is not allowed by Access-Control-Allow-Methods in preflight response.
...全文
273 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

87,910

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧