I am trying to pass value to the server in ionic using http but i am getting an error - ionic-framework

see the bellow sample code which i am trying to send it to the server
var serializedData = $.param({
api: key,
user: $scope.user.username
});
$http({
method: 'POST',
url: URL+"login_master/login",
data: serializedData,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}})....

Related

axios POST get 400

This is driving me crazy!
Exactly the same POST request works fine in Insomina per screenshot below:
The only header Insomina has is: Content-Type: application/json.
Now, the same request in code (I even copied the code generated from Insomnia for axios) via axios in Typescript:
const saveReqConfig: AxiosRequestConfig = {
method: 'POST',
url: 'THE SAME URL USED IN Insomina',
timeout: 3000,
data: {
name: `TestName`,
uri: `TestURI`,
statusCode: '200',
simulatedLatency: '0',
contentType: "application/json",
tags: '',
response: 'testing...',
type: 'VA',
},
headers: {
'Content-Type': 'application/json',
}
}
const normalAxios = axios.create();
const test = await normalAxios.request(saveReqConfig);
Don't understand why I am getting AxiosError: Request failed with status code 400 from code but the same request works fine in Insomina.
I think you did not set the headers correctly or you may not have setup the .create() properly.
Something like this:
const instance = axios.create({
url: '/post',
baseURL: 'https://httpbin.org',
method: 'POST',
timeout: 1000,
headers: {
Content-Type: 'application/json' // <- set your headers
}
});
let res = await instance.request({ // <- pass the data here
data: { // This should be whatever you want to post to this url. I just copied what you had.
name: `TestName`,
uri: `TestURI`,
statusCode: '200',
simulatedLatency: '0',
tags: '',
response: 'testing...',
type: 'VA',
}
});
Are you sure you need to use the .create() factory? The normal post like this might suite your needs better?
const data= { title: 'Axios POST Request Example' };
const headers = {
Content-Type: 'application/json'
};
axios.post('url', data, { headers }).then(response => console.log(response.data.title);
Posting here in case it helps someone.
It turned out that I couldn't post the request programmatically is because of lack of a TLS certificate. I didn't know that Insomnia has the option to disable the TLS and that's why it works in Insomnia.
To disable TLS (Do NOT do this in production!) from node with axios, create an instance of axios with a https agent setting rejectedUnauthorized to false e.g.
const instance = axios.create({
httpsAgent: new https.Agent({
rejectedUnauthorized: false
})
});
Also, set the environment variable as:
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';

Why the server responded with a status of 400

I am trying to create a sharepoint list using REST call. But i am getting error message: 'The server responded with a status of 400.'
Below is my code. Not able to understand where I am doing mistake:
url: https://abcTest.sharepoint.com/sites/dev/_api/web/lists.
digest: I am getting from a different function call.
const response = await fetch(url, {
method: 'POST',
credentials: 'include',
headers: {
'Accept': 'application/json;odata=verbose',
'Content-Type': 'application/json;odata=nometadata',
'X-RequestDigest': digest
},
body: JSON.stringify({
__metadata: {
type: 'SP.List`
},
AllowContentTyes: true,
BaseTemplate: 100,
ContentTypesEnabled: true,
Description: 'List description',
Title: 'MyList'
})
});
I think you should change
Accept: 'application/json;odata=verbose'
===> 'Accept': 'application/json;odata=verbose'
And : method: 'POST'` ===> method: 'POST'
Make sure parameter is json data.

How to use Sanity's assets HTTPS API and send a filename through the query?

I am using axios for the request module. I just want to be able to specify the filename of the image and can't figure out how to do this with this endpoint:
const { data } = await axios({
method: `post`,
url: `https://${projectId}.api.sanity.io/v1/assets/images/${dataset}`,
data: body, // readable stream for image here
headers: {
"Content-Type": contentType || `application/json`,
Authorization: `Bearer ${process.env.SANITY_TOKEN}`
},
})
I don't really want to use the #sanity/client.
Just need to add a Query String to the end of the url:
https://${projectId}.api.sanity.io/v1/assets/images/${dataset}?filename=myImage.jpg

403 forbidden and 400 bad request errors while adding and deleting items to SharePoint list using REST

I'm new to SharePoint development. I'm Trying to develop simple SharePoint App using SharePoint online. I have a List named 'Products' in my site collection. In my app I wrote the following code to add and delete items to that list
function addProduct(product) {
var executor;
executor = new SP.RequestExecutor(appwebUrl);
var url = appwebUrl +"/_api/SP.AppContextSite(#target)/web/lists/getbytitle('Products')/items/?#target='" + hostwebUrl+"'";
executor.executeAsync({
url: url,
method: "POST",
body: JSON.stringify({__metadata: { type: 'SP.Data.ProductsListItem' },
Title: product.ProductName(),
ProductId: product.ProductId(),
ProductName: product.ProductName(),
Price:product.Price()
}),
headers: {
"Accept": "application/json; odata=verbose",
"content-type": "application/json;odata=verbose",
},
success: successProductAddHandler,
error: errorProductAddHandler
});
}
function successProductAddHandler(data) {alert('added successfully') }
function errorProductAddHandler(data, errorCode, errorMessage) { alert('cannot perform action') }
function deleteProduct(product) {
var executor;
executor = new SP.RequestExecutor(appwebUrl);
var url=appwebUrl+"/_api/SP.AppContextSite(#target)/web/lists/getbytitle('Products')/items('" + product.ID() + "')/?#target='" + hostwebUrl + "'";
executor.executeAsync({
url: url,
method: "POST",
headers: {
"IF-MATCH": "*",
"X-HTTP-Method": "DELETE"
},
success: successProductAddHandler,
error: errorProductAddHandler
});`
Im getting 403 error code when I call addProduct,
and 400 error code when I call deleteProduct.
I'm able to get the list items and display.
I tried adding X-RequestDigest": $("#__REQUESTDIGEST").val() but it did not work
If I include "Accept": "application/json; odata=verbose" in a request header for deleteProduct(), and when I call deleteProduct, two requests are going to server
/sites/productsdev/productsapp/_api/contextinfo (getting digest value)
/sites/ProductsDev/ProductsApp/_api/SP.AppContextSite(#target)/web/lists/getbytitle('Products')/items(itemid)/?#target='mysitecollectionurl' (using the digest value returned by the above call for X-RequestDigest)
Whenever you are doing any POST operation in SharePoint 2013 using REST API you have to pass below snippet in header
"X-RequestDigest": $("#__REQUESTDIGEST").val()
eg
headers: { "Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val() }

Google Docs API: cannot set document title

I am trying to upload a file using Node and Google Docs REST API. I can upload the file just fine if I don't include the metadata, but it will always be uploaded as 'Untitled'.
But when I include the meta data I get the following error after sending my atom data and attempting to continue with the file upload:
ParseException - Content is not allowed in prolog
This is my first request to create an upload session and get a resumable-media-link
var meta = '<?xml version="1.0" encoding="UTF-8"?>'
meta+= '<entry xmlns="http://www.w3.org/2005/Atom" xmlns:docs="http://schemas.google.com/docs/2007">'
meta+= '<category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/docs/2007#document"/>'
meta+= '<title>Test</title></entry>'
var options = {
host: 'docs.google.com',
path: '/feeds/upload/create-session/default/private/full',
method: 'POST',
headers: {
'Host' : 'docs.google.com',
'Content-Length' : meta.length,
'Content-Type': 'application/atom+xml',
'GData-Version' : 3,
'Authorization' : 'GoogleLogin auth=' + authToken,
'X-Upload-Content-Type' : 'application/msword',
'X-Upload-Content-Length' : 31232
}
}
var req = https.request(options, function (res) {
// make 2nd request
});
req.end(meta);
This is what my 2nd request looks like after getting the resumable-media-link
var options = {
host: 'docs.google.com',
path: resumableMediaLink,
method: 'PUT',
headers: {
'Content-Length': data.length,
'Content-Type': 'application/msword',
'Content-Range': 'bytes 0-' + (data.length-1) +'/'+ data.length
}
}
var req = https.request(options, function (res) {
res.on('data', function (chunk) {
// ...
});
});
req.write(data);
req.end();
It seems like I am sending the atom data incorrectly. Any ideas of what I could be doing wrong?
I figured out what I was doing wrong.
I needed to set the 'Slug' header in the first POST request to initiate a resumable session.
I had it in the following request.