server
const express = require('express')
const app = express()
const bodyParser = require('body-parser')
// app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
// 解决跨域的问题
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
// res.header("Access-Control-Allow-Headers", "Content-Type");
// res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
// res.header("X-Powered-By",' 3.2.1')
// res.header("Content-Type", "application/json;charset=utf-8");
next();
});
app.get('/user', function (req, res) {
res.send('Get请求成功')
})
app.post('/user', (req, res) => {
console.log(req.body);
res.send('Post请求成功')
})
app.listen(3000, () => {
console.log('服务器启动成功');
})
client
function ajax(type, params) {
let { url, data } = params
return new Promise((reslove, reject) => {
let xhr = new XMLHttpRequest()
if (type === 'get') {
data = null
xhr.open('get', url)
} else if (type === 'post') {
xhr.open('post', url, true)
// xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
xhr.setRequestHeader('Content-Type', 'application/json')
}
xhr.onreadystatechange = function () {
if (this.readyState == 4) {
if (this.status === 200) {
reslove(this.responseText)
} else {
reject('请求信息有误')
}
}
}
xhr.send(JSON.stringify(data))
})
}
ajax('get', {
url: 'http://localhost:3000/user'
}).then(res => {
console.log(res);
}).catch(res => {
console.log(res);
})
// ajax('post', {
// url: 'http://localhost:3000/user',
// data: {
// username: 'zs',
// age: 20
// }
// }).then(res => {
// // console.log(res);
// }).catch(res => {
// console.log(res);
// })