server

  1. const express = require('express')
  2. const app = express()
  3. const bodyParser = require('body-parser')
  4. // app.use(bodyParser.urlencoded({ extended: false }))
  5. app.use(bodyParser.json())
  6. // 解决跨域的问题
  7. app.all('*', function(req, res, next) {
  8. res.header("Access-Control-Allow-Origin", "*");
  9. // res.header("Access-Control-Allow-Headers", "Content-Type");
  10. // res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
  11. // res.header("X-Powered-By",' 3.2.1')
  12. // res.header("Content-Type", "application/json;charset=utf-8");
  13. next();
  14. });
  15. app.get('/user', function (req, res) {
  16. res.send('Get请求成功')
  17. })
  18. app.post('/user', (req, res) => {
  19. console.log(req.body);
  20. res.send('Post请求成功')
  21. })
  22. app.listen(3000, () => {
  23. console.log('服务器启动成功');
  24. })

client

  1. function ajax(type, params) {
  2. let { url, data } = params
  3. return new Promise((reslove, reject) => {
  4. let xhr = new XMLHttpRequest()
  5. if (type === 'get') {
  6. data = null
  7. xhr.open('get', url)
  8. } else if (type === 'post') {
  9. xhr.open('post', url, true)
  10. // xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
  11. xhr.setRequestHeader('Content-Type', 'application/json')
  12. }
  13. xhr.onreadystatechange = function () {
  14. if (this.readyState == 4) {
  15. if (this.status === 200) {
  16. reslove(this.responseText)
  17. } else {
  18. reject('请求信息有误')
  19. }
  20. }
  21. }
  22. xhr.send(JSON.stringify(data))
  23. })
  24. }
  25. ajax('get', {
  26. url: 'http://localhost:3000/user'
  27. }).then(res => {
  28. console.log(res);
  29. }).catch(res => {
  30. console.log(res);
  31. })
  32. // ajax('post', {
  33. // url: 'http://localhost:3000/user',
  34. // data: {
  35. // username: 'zs',
  36. // age: 20
  37. // }
  38. // }).then(res => {
  39. // // console.log(res);
  40. // }).catch(res => {
  41. // console.log(res);
  42. // })