## 這個是我的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="https://bbs.csdn.net/topics/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.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/65589.html
標籤:JavaScript
