I want to use the cognitive search to store usernames and levels of a browser game. There should be an option to create a new username in the web frontend. The idea is, that the user enters a username and submits via button. Then these username should be saved in a cognitive search document.
MyiIssue: I am getting a cors error in browser console:
Access to XMLHttpRequest at 'https://XXXXXXX.search.windows.net/indexes/users/docs/index' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
The same issue occurs when I deploy it to a azure static web app.
The CORS settings at azure allow all origins.
Regarding to Azure Search and CORS issue with PUT, it is not possible to modify the data in this way. I am new to programming, how can it be done in another way (serverless function?)?
My code:
OnSubmitCreate(){
console.log('Create started')
let data = JSON.stringify({
"value": [
{
"@search.action": "mergeOrUpload",
"id": this.createName,
"username": this.createName,
"level": 1
}
]
});
let config = {
method: 'post',
url: 'https://XXXXXXXXXXX.search.windows.net/indexes/users/docs/index?api-version=2020-06-30',
headers: {
'api-key': 'XXXXXXXXXXXXXXXXXxx',
'Content-Type': 'application/json'
},
data : data
};
Thanks in advance!
CodePudding user response:
I`ve solved it with creating a azure function using javascript. When I call the URL, the write to cognitive search will be done.
So I technically am doing a http rest call (push).
index.js
var https = require('https');
module.exports = async function (context, req) {
context.log('JavaScript HTTP trigger function processed a request.');
var username = context.bindingData.username;
var level = context.bindingData.level;
let data = JSON.stringify({
"value": [
{
"@search.action": "mergeOrUpload",
"id": username,
"username": username,
"level": level
}
]
})
var options = {
host: 'XXXXXXXXXXX.search.windows.net',
path: '/indexes/users/docs/index?api-version=2020-06-30',
port: 443,
method: 'POST',
headers: {
'api-key': 'XXXXXXXXXXXX',
'Content-Type': 'application/json'
},
body: data
};
var req = https.request(options, function(res) {
console.log('STATUS: ' res.statusCode);
console.log('HEADERS: ' JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' chunk);
});
});
req.on('error', function(e) {
console.log('problem with request: ' e.message);
});
// write data to request body
req.write(data);
req.end();
context.res = {
// status: 200, /* Defaults to 200 */
body: req
};
}
function.json
{
"bindings": [
{
"authLevel": "function",
"type": "httpTrigger",
"direction": "in",
"name": "req",
"methods": [
"get",
"post"
],
"route": "data/{username:alpha}/{level:int?}"
},
{
"type": "http",
"direction": "out",
"name": "res"
}
]
}