简体   繁体   中英

request.body is undefined in node post request

I am trying to handle post ajax request at node server. My problem is, I am getting request body 'undefined'. kindly help me to understand if I am doing wrong. Following is the code I am using.

  • Ajax request code:

function sendRequest() {

    let http = new XMLHttpRequest();
    let url = 'http://<hostname>:3000/checkRequest';    
    let data = {};
    data.name = "nameString";
    data.age = "ageString";        
    http.open('POST', url, true);        
    //Send the proper header information along with the request
    http.setRequestHeader('Content-type','application/x-www-form-urlencoded');
    http.send(JSON.stringify(data));   
    http.onreadystatechange = function() {//Call a function when the state changes.
        if(http.readyState === 4 && http.status === 200) {
            alert(http.responseText);
        }
    };   
}
  • Request handler code:

     // create express app const app = express(); // parse application/x-www-form-urlencoded app.use(bodyParser.urlencoded({ extended: true })); // parse application/json app.use(bodyParser.json()); // middleware route that all requests pass through app.use((request, response, next) => { console.log('Server info: Request received'); let origin = request.headers.origin; // only allow requests from trusted origins if (originWhitelist.indexOf(origin) > -1) { response.header('Access-Control-Allow-Origin', origin); } // only allow get and post requests, separate methods by comma eg 'GET, POST' response.header('Access-Control-Allow-Methods', 'GET, POST'); response.header('Access-Control-Allow-Headers', 'X-Requested-With,content-type'); response.header('Access-Control-Allow-Credentials', true); // push through to the proper route next(); }); app.post('/checkRequest', (request, response) => { console.log(request.body.name) //undefined } 

You're sending the result of JSON.stringify with a content type of application/x-www-form-urlencoded . If you want to submit JSON change the content type to application/json . If you want to submit url encoded use new URLSearchParams(data).toString() instead of JSON.stringify(data) .

I personally recommend sending data as JSON.

https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/toString

I need to make the following changes:

1: Use the content type json: http.setRequestHeader('Content-type','application/json');

2: I need to add request type 'OPTIONS' in my node application because if we change default content-type browser send an extra 'OPTIONS' type request before sending actual post request (reference request screen shot added).

For more details refer: https://upload.wikimedia.org/wikipedia/commons/c/ca/Flowchart_showing_Simple_and_Preflight_XHR.svg

Updated allow methods are:

response.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');

我的要求画面

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM