Update: I have changed my Services and Controller as follows and am now receiving an Error 412 (HTTP/1.1 412 Precondition Failed). Here is my updated code:
Service:
appServices.factory('appType', ['$resource', function ($resource) {
return $resource("/_api/web/lists/getbytitle('Todo Types List')/Items(:Id)", { Id: "#Id" },
{
'query': { method: "GET", isArray: false, headers: { 'Accept': 'application/json;odata=nometadata' } },
'update': { method: 'PATCH', headers: { 'Accept': 'application/json;odata=nometadata' } },
'save': { method: 'POST', headers: { 'Accept': 'application/json;odata=nometadata', 'content-type': 'application/json;odata=nometadata', 'X-RequestDigest': $("#__REQUESTDIGEST").val() } },
'delete': { method: 'DELETE', headers: { 'Accept': 'application/json;odata=nometadata', 'content-type': 'application/json;odata=nometadata', 'X-RequestDigest': $("#__REQUESTDIGEST").val() }, 'IF-MATCH': "*" },
}
);
}]);
Relevant part of Controller:
$scope.removeType = function (type) {
appType.delete({ Id: type.Id });
console.log("Deleted" + type.ID);
}
}]);
Original Post:
I am attempting to delete an item/row in an Angular App built on top of SharePoint 2013, but when I am attempt the delete it appears to process, except nothing is removed from the SharePoint list. Using the network tab in IE, I get a 400 error.
Here is my controller:
appControllers.controller('appSettingsCtrl', ['$scope', 'appTypes', function ($scope, appTypes) {
// Retrieve Types
$scope.types = [];
appTypes.query({}, function (data) {
$scope.types = data.value;
});
// Create Types
var typeEntry = new appTypes;
$scope.addType = function () {
console.log("Clicked");
typeEntry.Title = $scope.itemtype;
typeEntry.$save();
}
// Delete types
$scope.removeType = function (type) {
appTypes.delete({}, { Id: type.ID });
console.log("Deleted" + type.ID);
}
}]);
Here is my HTML:
<table class="table table-striped">
<tr>
<th>Type</th>
<th>
Action
</th>
</tr>
<tr ng-repeat="type in types" id="type{{type.Id}}">
<td>
{{type.Title}}
</td>
<td>
<button type="button" class="btn btn-danger" data-ng-click="removeType(type)">Delete</button>
</td>
</tr>
</table>
Here is my service:
appServices.factory('appTypes', ['$resource', function ($resource) {
return $resource("/_api/web/lists/getbytitle('Todo Types List')/Items", {Id: "#Id" },
{
'query': { method: "GET", isArray: false, headers: { 'Accept': 'application/json;odata=nometadata' } },
'update': { method: 'PATCH', headers: { 'Accept': 'application/json;odata=nometadata' } },
'save': { method: 'POST', headers: { 'Accept': 'application/json;odata=nometadata', 'content-type': 'application/json;odata=nometadata', 'X-RequestDigest': $("#__REQUESTDIGEST").val() } },
'delete': { method: 'DELETE', headers: { 'Accept': 'application/json;odata=nometadata', 'content-type': 'application/json;odata=nometadata', 'X-RequestDigest': $("#__REQUESTDIGEST").val(), 'IF-MATCH': '*' } },
}
);
}]);
Here is some sample JSON:
{
"value": [
{
"FileSystemObjectType": 0,
"Id": 5,
"ID": 5,
"ContentTypeId": "0x01004CE051F4BDBACB43BB22C234F8F497FE",
"Title": "Type 1",
"Modified": "2015-03-13T18:35:09Z",
"Created": "2015-03-13T18:35:09Z",
"AuthorId": 12,
"EditorId": 12,
"OData__UIVersionString": "1.0",
"Attachments": false,
"GUID": "9ceee022-a418-43d4-86b1-1de6d68edc47"
}
]
}
I am using following headers when removing a item from a list.
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"If-Match": "*",
"X-Http-Method": "DELETE".
For me it works. Hope it helps to you too.
Blame this error on having a small typo that malformed the header (The If-Match was outside of the headers:. This is correct:
'delete': { method: 'DELETE', headers: { 'Accept': 'application/json;odata=verbose', 'content-type': 'application/json;odata=verbose', 'X-RequestDigest': $("#__REQUESTDIGEST").val(), 'IF-MATCH': '*' } }
Related
An example of the rapidapi google translate API code for the JavaScript fetch method is:
fetch("https://google-translate1.p.rapidapi.com/language/translate/v2", {
"method": "POST",
"headers": {
"x-rapidapi-host": "google-translate1.p.rapidapi.com",
"x-rapidapi-key": "MY-API-KEY",
"accept-encoding": "application/gzip",
"content-type": "application/x-www-form-urlencoded"
},
"body": {
"source": "en",
"q": "Hello, world!",
"target": "es"
}
})
.then(response => {
console.log(response);
})
.catch(err => {
console.log(err);
})
Now I copied it, and used it for the React component as follows:
fetch("https://google-translate1.p.rapidapi.com/language/translate/v2", {
method: "POST",
body: {
"source": "en",
"q": "Hello, world!",
"target": "es"
},
headers: {
"x-rapidapi-host": "google-translate1.p.rapidapi.com",
"x-rapidapi-key": "MY-API-KEY",
"accept-encoding": "application/gzip",
"content-type": "application/x-www-form-urlencoded"
}
})
.then(response => {
console.log(response);
})
.catch(err => {
console.log(err);
})
After running the program, I get the error "POST https://google-translate1.p.rapidapi.com/language/translate/v2 502 (Bad Gateway)" on the console!
How can I have a healthy connection to the server?
this code solved the same problem for me
<script>
const key = "your key"
const qs = obj => {
return new URLSearchParams(obj).toString();
}
const word = "Hello, world";
const data = qs({
q: word,
source: "en",
target: "es",
})
const options = {
method: "POST",
url: "https://google-translate1.p.rapidapi.com/language/translate/v2",
headers: {
"content-type": "application/x-www-form-urlencoded",
"x-rapidapi-key": key,
"x-rapidapi-host": "google-translate1.p.rapidapi.com",
},
data: data,
};
axios.request(options).then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.error(99, error);
});
</script>
My url if opened on browser gives the following error:(attached image)
Body of my api call looks like below :
{
"entityId": 4071,
"listViewId": 0,
"asLookup": false,
"retrieveAllFields": true,
"fullTextSearch": "",
"query": [
],
"pagination": {
"pageNumber": 0,
"recordsCountPerPage": 0
},
"sorting": {
"fieldId": 0,
"direction": 0
}
}
I am calling api in react native using fetch below :
try {
let response = await fetch('url', {
method: 'POST',
headers: {
'tenantid': '1',
'Content-Type': 'application/json',
'language': '0',
},
body: JSON.stringify({
entityId: 4071,
listViewId: 0,
asLookup: false,
retrieveAllFields: true,
fullTextSearch: "",
query: [
],
pagination: {
pageNumber: 0,
recordsCountPerPage: 0
},
sorting: {
fieldId: 0,
direction: 0
}
})
})
let json = await response.json();
console.log("This is response" + json)
this.setState({records: json.results, isFetching:false});
}catch(error){
this.setState({errorMessage:error})
console.log("This is error"+error)
}
This gives me response : Network failed request. Also tried with the inverted commas, still same response. I am newbie in react native but I have made api calls in the past but this one wouldnt work. If anyone can look into this, would be of great help!
did you use the correct url ?
it should looks like something like this
fetch('https://mywebsite.com/endpoint/', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue'})
}).then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
});
maybe you should look on the documentations
https://reactnative.dev/docs/network
I update my RN app from 0.58.3 version to 0.59.4 and instead of bodyText server return bodyBlob now
I tried to use response.json() func but it doesn't help
fetch(`http://someserver `, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Accept-Language': 'ru,en;q=0.9',
},
body: '{"login":"root","password":"root"}'
})
.then((response) => {
console.log(response.json());
});
response i get is like this:
{
"type": "default",
"status": 200,
"ok": true,
"headers": {
"map": {
"x-xss-protection": "1",
"set-cookie": "jwt=eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyLWNvZGUiOiJyb290LXVzZXIiLCJleHAiOjE1NTU0MjY0Mjl9.UaHzsIil8t9HtgrBF8JN0c2W-eIIkDEmb6GvO9Do0-A;Expires=Tue, 16 Apr 2019 14:53:49 +0000;Path=/;HttpOnly;SameSite=Strict",
"connection": "keep-alive",
"content-length": "360",
"content-type": "application/json;charset=utf-8",
"date": "Tue, 16 Apr 2019 13:53:49 GMT",
"server": "nginx/1.15.10"
}
},
"url": "***",
"_bodyInit": {
"_data": {
"size": 360,
"offset": 0,
"blobId": "3397402a-12dd-4dd9-8980-90924aeb416d"
}
},
"_bodyBlob": {
"_data": {
"size": 360,
"offset": 0,
"blobId": "3397402a-12dd-4dd9-8980-90924aeb416d"
}
}
}
instead of normal bodyText i get bodyBlob
Sorry, I am late with the answer. I hope it will be helpful for others.
Be careful, response.json() returns promise.
fetch(`http://someserver `, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Accept-Language': 'ru,en;q=0.9',
},
body: '{"login":"root","password":"root"}'
})
.then((response) => {
response.json().then(res => {
console.log(res);
})
});
I am using the rest api of outlook for sending the request. But when i am calling this with above code, in console i am getting error
unhandled exception
$scope.createEvents = function(){
alert("here");
var url = "https://outlook.office.com/api/v2.0/$metadata#Me/Calendars";
$scope.token = "AQABAAIAAADX8GCi6Js6SK82TsD2Pb7rFu9WBTIi5a6r4Up0vk8NCmPR719K3Uiz7NPUBoT9RwewzSWjPfUIybYn9fVVF2dhQ8b0ObN3oIv5Tq91GwZiTuyBhWZ_s07uDJpCUh40K4Bn2F5eEP9TAp8-5eMY0hfyXb4vIukQwTAe9yXCG75WUS08M7m-_kFbtx-TVq-Y2-SKh8Ut7-v4UQq4NYhlf5LQC1arNbwAZVndfND1vSNGcs1BVJboWd7bcgohHecaR57cAuFav2vfsVEm8n3_IKnlapHzWsyXOw7gXnxTmH2pkfAie0LCiQv8C8nQRnYnLquaWKg6b_ZzTl4ela0EwC9cN74BVMQHFWm6NY1EVM8s-HYevrT8R-WwkAUJXprP40Jp-weLY4-K7vOGk0N0n6fQIeu_WoORIZ18-oKxda6j4XunmrLbWEapQy-Oms9BIAs-AZIVN6Ph1zxQk3CC1bbGK6QkiiL4c2Sgrx_6YoxZt1cMh36pjhbe_TxpC2alk5zJineTK0AZUdGJQWGoy-9fTwtzTbYiaRaV4rispV-q-yiYzpWQ1UWROIPZ5qDq2jlCV7ovTDCWhNd_JgKzzHf-2wANBun9WcX924UVcLkkfvh6XU-QxCo1N6gfGYGUwNNJA1kTZjSyxgKSOAKGxKXz96r5qbtJp34Ci9lEO-PpSeLAL5gHoUOX_PlbM_FO4mLcNEu_fB0Us-5sbV8pKPU-WnfLq3PI8gK3lCi5D_itjesuex1f-o1d1vJ3M4jvx-sgAA";
var add_events = {
"Subject": "Discuss the Calendar REST API",
"Body": {
"ContentType": "HTML",
"Content": "I think it will meet our requirements!"
},
"Start": {
"DateTime": "2016-10-10T18:00:00",
"TimeZone": "Pacific Standard Time"
},
"End": {
"DateTime": "2016-10-10T19:00:00",
"TimeZone": "Pacific Standard Time"
},
"Attendees": [
{
"EmailAddress": {
"Address": "nishanth.singh#subex.com",
"Name": "Nishanth Kumar Singh"
},
"Type": "Required"
}
]
};
$http({
method: 'JSOPN',
url: url,
headers:{
'Authorization':'Bearer '+$scope.token,
'Content-Type': "application/json",
'Accept': 'application/json;odata.metadata=minimal',
'Access-Control-Allow-Origin':'*'
},
data: add_events
}).Succes(function (response) {
alert("Saved")
});
}
Replace
}).Succes(function (response) {
with
}).success(function (response) {
You have used upper case Success in your code & the spelling is incorrect as well. Let me know once you made this change.
Try to use .then() rather than success() as success() has been deprecated.
Update 1
Since you are using version 1.6, use .then(). success() is deprecated as I said
$http({
method: 'JSOPN',
url: url,
headers:{
'Authorization':'Bearer '+$scope.token,
'Content-Type': "application/json",
'Accept': 'application/json;odata.metadata=minimal',
'Access-Control-Allow-Origin':'*'
},
data: add_events
}).then(function (response) {
alert("Saved")
});
Update 2
You are now facing CORS issue. for quick fix try chrome plugin.
Get proper header to complete the request or you need to config the server to handle such requests.
change method: 'JSOPN' to
method: 'JSON'
I am working in a project where to search from firebase data using elastic search and trying to add data to elastic using angularjs but giving error as :
{"data":"","status":0,"config":{"method":"PUT","transformRequest":[null],"transformResponse":[null],
my code is:
var inputJson =
{
"mappings": {
"carprev": {
"properties": {
"agepolicy33": {
"type": "text"
},
"aircondition33": {
"type": "text"
},
"year33": {
"type": "integer"
}
}
}
}
}
var corsHeaders = {
origin: ["*"],
headers: ['Origin', 'X-Requested-With', { 'Content-Type':
'application/x-www-form-urlencoded' }],
credentials: true,
additionalHeaders: ['access-control-allow-headers', 'Access-Control-
Allow-Origin, Access-Control-Allow-Headers, Origin, X-Requested-With,
Content-Type, CORRELATION_ID'],
additionalExposedHeaders: ['access-control-allow-headers', 'Access-
Control-Allow-Origin, Access-Control-Allow-Headers, Origin, X-
Requested-With, Content-Type, CORRELATION_ID']
};
$http({
method: "PUT",
// headers: ['Origin', 'X-Requested-With', 'Content-Type'],
url: "http://xx.xxx.xxx.xxx/elasticsearch/test/5",
data: inputJson
}).then(function mySuccess(response) {
console.log(response);
}, function myError(err) {
var cjson = JSON.stringify(err);
console.log(err);
});
but the same json in inserted into elasticsearch using postman and query data to retrieve from elastic
if anyone can resolve, appreciated
You can try changing the content type to json.
$http({
method: "PUT",
headers: {'Content-Type': 'application/json'},
url: "http://xx.xxx.xxx.xxx/elasticsearch/test/5",
data: inputJson
}).then(function mySuccess(response) {
console.log(response);
}, function myError(err) {
var cjson = JSON.stringify(err);
console.log(err);
});