I have a function sending an object to NodeJS.
function addRequest(request_item){
var request = new XMLHttpRequest;
request.open("GET", "http://localhost:3000/add_register_request"+"?request_item="+request_item)
request.send(request_item);
console.log("Sent");
document.location.reload(true);
};
request_item is the object.
app.get('/add_register_request', function(req,res){
console.log("ADDDD")
var request = req.query.request_item
console.log(`SQL is ${request}`) //This gives {object Object}
})
JSON.stringify(request) simply returns '{object Object}'. The only difference is it is now in quotes.
How can I access the object in my NodeJS as well? Thanks in advance!
If request_item
is an object and you concatenate it to a string, it will turn into the string object Object you're receiving and seeing in the /add_register_request
endpoint.
const request_item = { foo: 'bar' }; const request_string = "http://localhost:3000/add_register_request"+"?request_item=" + request_item; console.log(request_string);
If you're trying to send data to the back end in order to save it to some database or something of the sort, you should use the POST verb instead of GET and send the data inside the body of the request and not as a param.
Also, i think you may have forgotten the parenthesis when initializing new XMLHttpRequest
. I think it should be new XMLHttpRequest()
Query variables accept strings and not Objects. If you want to pass a whole js object, you might encode it to JSON and then further encode it to base64. Another strategy might be to convert every request_item
attribute to a query. Or you might want to use another HTTP method that contains a body to send the object into.
function addRequest(request_item){
var request = new XMLHttpRequest;
request.open(
"GET",
"http://localhost:3000/add_register_request"
+"?request_item_value_1="+request_item.value_1
+"&request_item_value_2="+request_item.value_2
)
request.send(request_item);
console.log("Sent");
document.location.reload(true);
};
then in your server
app.get('/add_register_request', function(req,res){
console.log("ADDDD")
var request = {
value_1: req.query.request_item_value_1,
value_2: req.query.request_item_value_2,
}
console.log(`SQL is ${request}`) //This gives {object Object}
})
Where request_item.value_1
and request_item.value_1
are strings or values that can be concatenated to strings
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.