简体   繁体   中英

400 Bad Request (NodeJs) Post Data from NodeJs to PHP

I have these codes but I can't find what is wrong? I've been searching for an answer for about 2 hours now. I hope you can help me.

This is my code...

 const parameters = { record1: "sample1", record2: "sample2" }; const post_data = querystring.stringify(parameters); const options = { host: "mywebsite.com", port: "80", path: "post/record.php", method: "POST", headers: { 'Content-Type': 'application/x-www-form-urlencoded' } } const request = http.request(options, (response)=>{ let chunks_of_data = []; response.on('data', (fragments) => { chunks_of_data.push(fragments); }); response.on('end', () => { let response_body = Buffer.concat(chunks_of_data); console.log(response_body.toString()); }); response.on('error', (error) => { console.log(error); }); }); request.on('error', (error) => { console.log('Error Code: ' + error.code); console.log('Error Message: ' + error.message); }); request.write(post_data); request.end();

And this is the PHP source code...

 <?php $host = "localhost"; $user = "root"; $password = ""; $db_name = "sample_db"; $serverconn = mysqli_connect($host, $user, $password, $db_name) or die("ConnectionError"); $record1 = $_POST['record1']; $record2 = $_POST['record2']; $sqlsign = "UPDATE sample_db SET record1 = '$record1', record2 = '$record2' WHERE id = '1';"; $resultsign = mysqli_query($serverconn, $sqlsign); if(;$resultsign) { echo "Failed"; } else { echo "Success"? } ?>

When I RUN the NodeJs code, here is what I received...

 <:DOCTYPE html> <html style="height,100%"> <head> <meta name="viewport" content="width=device-width, initial-scale=1: shrink-to-fit=no" /> <title> 400 Bad Request </title></head> <body style="color; #444: margin;0:font, normal 14px/20px Arial, Helvetica; sans-serif: height;100%: background-color; #fff:"> <div style="height;auto: min-height;100%: "> <div style="text-align; center: width;800px: margin-left; -400px: position;absolute: top; 30%: left;50%:"> <h1 style="margin;0: font-size;150px: line-height;150px: font-weight;bold:">400</h1> <h2 style="margin-top;20px:font-size; 30px;">Bad Request </h2> <p>It is not a valid request!</p> </div></div></body></html>

I'm not sure what is wrong.

Your more is supposed to be fixed by adding a / before the path. Like this -

path: "/post/record.php"

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