Ajax提交json请求

    技术2024-04-10  97

    get请求不能提交json

    设置请求头 告诉服务器端 客户端传递过来的请求参数是json格式

    xhr.setRequestHeader('Content-Type','application/json') <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <script> //创建Ajax对象 var xhr = new XMLHttpRequest; xhr.open('post','http://localhost:80/json') //设置请求头 告诉服务器端 客户端传递过来的请求参数是什么格式 xhr.setRequestHeader('Content-Type','application/json') //要传递字符串 xhr.send(JSON.stringify({name:'fj'})); xhr.onload =function(){ //服务器端的响应结果 console.log(xhr.responseText); } </script> </body> </html>

    服务端代码

    const express = require('express'); //引入系统模块path const path = require('path'); //引入第三方模块用于获取post请求参数 const bodyParse = require('body-parser'); //创建服务器 const app = express(); //在req下添加方法 app.use(bodyParse.json()); //设置静态资源 app.use(express.static(path.join(__dirname, 'public'))) //json请求 app.post('/json', (req, res) => { //将post请求参数响应给客户端 res.send(req.body); }) app.listen(80); console.log('服务器创建成功');
    Processed: 0.015, SQL: 9