I am sending some data from my website using an api to store in the GCP datastore. Its working upto storing in the datastore but now sending response to web app.
I used xmlhttp request method to pass the parameter to an api. In my api status code "200" is getting in the logs but the key (Auto-id of the data store in the datastore) passing from the status code 200 is not getting in the website.
website code:
<html>
<head>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<title> The Underpass/Login</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<div class="data" >
<h1>SignUp Here</h1>
<form method = "POST" >
<p>CityCode</p>
<input type="text" name="citycode" placeholder="Enter citycode" id="citycode"
pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}" title="Must contain at least one number and one uppercase and lowercase letter, and at least 6 or more characters">
<p>CountryCode</p>
<input type="code2" name="countrycode" placeholder="Enter countrycode" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}" title="Must contain at least one number and one uppercase and lowercase letter, and at least 6 or more characters" id="countrycode">
<button type="submit" name="submit" onclick="myFunction()">Submit</button> </br> </br> </br>
</form>
</div>
</body>
<script type="text/javascript">
function myFunction() {
var citycode, countrycode;
city = document.getElementById('citycode').value;
country = document.getElementById('countrycode').value;
var xhttp = new XMLHttpRequest();
var url = "https://my api url";
var sending = JSON.stringify({
"citycode": city,
"countrycode": country
});
xhttp.open("POST", url, true);
xhttp.send(sending);
它已成功将数据发送到api,但在下面的操作中,它未获取xhttp.onreadystatechange()中的响应。
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
console.log("status success");
alert(xhttp.responseText);
}
};
}
MY API:
const Datastore = require('@google-cloud/datastore');
const ProjectId = 'Addressbookxx';
exports.WebRegister = (req, res) => {
const datastore = Datastore({
projectId: ProjectId
});
const kind = 'Address';
const ID = datastore.key(kind);
var givendata = JSON.parse(req.body);
var citycode = givendata.citycode
var countrycode = givendata.countrycode;
var pattern=/(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/g;
if ((citycode.match(pattern)) && (countrycode.match(pattern))){
const address =
{
key: ID,
data: [
{
name : 'city code',
},
{
name : 'country code',
},
]
};
datastore.insert(address).then(() => {
const ID = entity[datastore.KEY];
var key = ID.id;
res.status(200).send({id:key});
// ===>在日志{id:key}中,但没有作为响应返回网站。
}).catch((err) =>{
res.status(400).send({status:"error during insertion"});
});
});
}
});
}
};
请帮助我解决此问题。 请向我建议一种执行此方法的方法(我想借助api在我的网站上将字符串存储在GCP数据存储中。我已经在GCP云函数中编写了一个函数,我在我的网站中将此API称为发送数据并进行存储。作为对我网站的回应,我需要存储数据的ID。)
谢谢。