I have the following piece of API documentation and I don't understand how to POST the compulsory parameters in red https://i.stack.imgur.com/ucYmT.png
I created the following request body:
var requestBody = JSON.stringify({
"title":"<p>message1</p>",
"since":1530535861,
"till":1562071860
});
And then my request is like this:
var requestUrlCreate='http://www.testsite.com/engine2/api/channel/47259/post/publish';
xmlhttp2.open('POST', requestUrlCreate, true);
xmlhttp2.setRequestHeader('Content-Type', 'application/json');
xmlhttp2.send(requestBody);
But every time I get error 500: "500 (Request processing failed; nested exception is java.lang.IllegalStateException: Current request is not of type [org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest]: "
I understand my request is wrong, maybe I misinterpreted the API documentation and the request body hasn't to be sent in JSON format. What do you think, how would you do it?
Many thanks for letting me know!
Related
I am trying to fetch data via external API using google app script but I keep getting Request failed for https://api.10000ft.com returned code 404. Truncated server response:
On debugging, it tells me response not defined. What could I be doing wrong?
Here is the code:
function fetchSheet() {
var response = UrlFetchApp.fetch('https://api.10000ft.com/api/v1/users//time_entries?from=2020-01-06&to=2020-01-14&auth=token');
Logger.log(response.getContentText());
}
I've tried to send the same request from Postman, and the message I received was "invalid or missing auth token", and not 404.
It seems like you need to add header fields.
You should try something like this (and check where to get the access token from):
function fetchSheet(accessToken) {
var headers = {
headers: {
Authorization: 'Bearer ' + accessToken
}
}
var response = UrlFetchApp.fetch('https://api.10000ft.com/api/v1/users/time_entries?from=2020-01-06&to=2020-01-14&auth=token', headers);
Logger.log(response.getContentText());
}
Also, the url seems not to fulfil REST's structure: .../users/HERE_SHOULD_BE_A_USER_ID/time_entries?...
I guess that your initial mistake with the double slash was that you've missed this path param.
I'm trying to access the response of my POST request in Postman via Post Request Script.
I added this 2 lines, under Pre-request Script
let response = pm.response.json();
console.log('JSON Response: ',response );
Then, I opened up my Postman console, before hit Send to make my POST request
I kept getting
There was an error in evaluating the Pre-request Script: TypeError: Cannot read property 'json' of undefined
Do I need to enable anything on Postman?
Pre-request scripts are ran before the request is sent. You do not have a response yet.
Try putting your script under the Tests tab, which is ran after a response is received.
In my case, there was a script that was screwing up my request. If you get the postman collection from someone else, check this and try to fix it. (in my case I don't need it so I deleted it)
You can try setting an environment variable, get it and parse it, I was created a POST requests to make a login and get a token to each request.
const echoPostRequest = {
url: pm.environment.get("url_login"),
method: 'POST',
header: 'Content-Type: application/json',
body: {
mode: 'raw',
raw: JSON.stringify({ email: pm.environment.get("user"),password: pm.environment.get("password") })
}
};
pm.sendRequest(echoPostRequest, function (err, res) {
console.log(err ? err : res.json());
pm.environment.set("login_response", res.json());
pm.environment.set("bearer_token", pm.environment.get("login_response").bearer_token);
});
was helping a friend and he had tried to make an adjustment to all requests in the collection.
I found in the documentation, how to remove
https://learning.postman.com/docs/writing-scripts/pre-request-scripts/
Please Make Sure That You Cleared Text Area Of PRE-REQUEST & TESTS TAB
By Clearing Text I Solved This Issue
Check if you SSL was turn off. If isn't, turn off.
Settings >> General >> SSL Certificate Verification
I'll start by saying I'm a bit of a newb when it comes to Javascript/React. I am attempting to communicate with my WCF endpoint server but I can’t seem to send any POST messages without getting a response:
OPTIONS http://###/testbuyTicket 405 (Method Not Allowed)
It seems that because I am sending it with content-type JSON it requires a ‘pre-flight’ and this is where it is failing.
This is my client code:
var headers = {
'headers': {
'Content-Type': 'application/json',
}
}
axios.post(call, data, headers).then(res => {
try {
if (res) {}
else {
console.log(res);
}
}
catch (err) {
console.log(err);
}
}).catch(function (error) {
console.log(error);
});
Here is the error details:
I don’t see why this pre-flight is failing. On the server I have already allowed everything I believe I need:
{"Access-Control-Allow-Origin", "*"},
{"Access-Control-Request-Method", "POST,GET,PUT,DELETE,OPTIONS"},
{"Access-Control-Allow-Headers", "X-PINGOTHER,X-Requested-With,Accept,Content-Type"}
[ServiceContract]
public interface IPlatform
{
[OperationContract]
[WebInvoke(UriTemplate = "testbuyTicket")]
TicketResponse TestBuyTicket(PurchaseRequest purchaseRequest);
}
Any help would be appreciated. I feel like I've tried everything. Thanks in adance.
I have found a solution, I'm not sure if it's the most elegant solution but it does work.
Basically I have an endpoint that the call should be directed too, but it only accepts POST requests, so I have added an OPTIONS endpoint with an empty method and it all appears to work now.
So I now have:
[ServiceContract]
public interface IPlatform
{
[OperationContract]
[WebInvoke(UriTemplate = "testbuyTicket")]
TicketResponse TestBuyTicket(PurchaseRequest purchaseRequest);
[OperationContract]
[WebInvoke(UriTemplate = "testbuyTicket", Method = "OPTIONS")]
TicketResponse TestBuyTicketOptions(PurchaseRequest purchaseRequest);
}
Doing this allows the server to respond to the OPTIONS call and then the POST call.
Thanks everyone for your assistance.
Big shoutout to #demas for the idea, see post Response for preflight has invalid HTTP status code 405 for more info
Like #charlietfl says, this doesn't appear to be a CORS issue, since you seem to be returning the headers OK (per the screenshot).
My guess is that your web server (Apache or whatever) doesn't allow OPTIONS requests - many only allow GET/POST/HEAD by default.
Probably a simple web server setting...
I am trying to post data from React component to spring boot controller.
I sent xhr requests like this, which failed with 400:
const valToSent = {
queueId: this.props.queueId,
flag: restFlag //value is '' or '1'
};
const xhr = new XMLHttpRequest();
xhr.open('post', '/display/clickNext.json', true);
xhr.setRequestHeader('Content-Type', 'application/json');
const data = JSON.stringify(valToSent);
xhr.send(data);
Then I tried this, which worked:
const xhr = new XMLHttpRequest();
xhr.open('post', `/display/clickNext.json?queueId=${this.props.queueId}&flag=${restFlag}`, true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send();
But I don't know why.n what is the difference between them?
I searched and found this question what's the difference between request payload vs form data as seen in chrome, if I understand it right, the best answer tells 'they differ in the Content-Type but not in the way data is submitted', so I am more confused why I am wrong and failed.
I really want to understand this problem, the template literals seem not so elegant by using it this way, more important, it seemed like it is about some basic concepts.
The first one is a sensibly arranged POST request that says it is sending JS in the body and sends JSON in the body.
The second one is … weird. It says it is sending Form Encoded data in the body, but actually sends nothing in the body while shoving the data (without proper escaping) into the query string.
To tell why the sensible request is getting a "400 Bad Request" error from the server would require that you debug the server side code.
I am trying to send a new push subscription to my server but am encountering an error "Uncaught (in promise) SyntaxError: Unexpected end of JSON input" and the console says it's in my index page at line 1, which obviously is not the case.
The function where I suspect the problem occurring (because error is not thrown when I comment it out) is sendSubscriptionToBackEnd(subscription) which is called in the following:
function updateSubscriptionOnServer(subscription) {
const subscriptionJson = document.querySelector('.js-subscription-json');
const subscriptionDetails = document.querySelector('.js-subscription-details');
if (subscription) {
subscriptionJson.textContent = JSON.stringify(subscription);
sendSubscriptionToBackEnd(subscription);
subscriptionDetails.classList.remove('is-invisible');
} else {
subscriptionDetails.classList.add('is-invisible');
}
}
The function itself (which precedes the above function):
function sendSubscriptionToBackEnd(subscription) {
return fetch('/path/to/app/savesub.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(subscription)
})
.then(function(response) {
if (!response.ok) {
throw new Error('Bad status code from server.');
}
return response.json();
})
.then(function(responseData) {
if (!(responseData.data && responseData.data.success)) {
throw new Error('Bad response from server.');
}
});
}
I have tried replacing single quotes with double quotes in the fetch call but that yields the same results.
I know that the JSON should be populated because it prints to the screen in the updateSubscriptionOnServer() function with subscriptionJson.textContent = JSON.stringify(subscription);, and I used that output in the google codelab's example server to receive a push successfully.
EDIT: Here is the JSON as a string, but I don't see a mistake in syntax:
{"endpoint":"https://fcm.googleapis.com/fcm/send/dLmthm1wZuc:APA91bGULRezL7SzZKywF2wiS50hXNaLqjJxJ869y8wiWLA3Y_1pHqTI458VIhJZkyOsRMO2xBS77erpmKUp-Tg0sMkYHkuUJCI8wEid1jMESeO2ExjNhNC9OS1DQT2j05BaRgckFbCN","keys":{"p256dh":"BBz2c7S5uiKR-SE2fYJrjPaxuAiFiLogxsJbl8S1A_fQrOEH4_LQjp8qocIxOFEicpcf4PHZksAtA8zKJG9pMzs=","auth":"VOHh5P-1ZTupRXTMs4VhlQ=="}}
Any ideas??
This might be a problem with the endpoint not passing the appropriate parameters in the response's header.
In Chrome's console, inside the Network tab, check the headers sent by the endpoint and it should contain this:
Example of proper response to allow requests from localhost and cross domains requests
Ask the API developer to include this in the headers:
"Access-Control-Allow-Origin" : "*",
"Access-Control-Allow-Credentials" : true
This happened to me also when I was running a server with Express.js and using Brave browser. In my case it was the CORs problem. I did the following and it solved the problem in my case:
(since this is an Express framework, I am using app.get)
-on the server side:
res.set({
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
});
-on client side I used Fetch to get data but disabled the CORS option
// mode: "no-cors" //disabled this in Fetch
That took care of my issues with fetching data with Express
This can be because you're not sending any JSON from the server
OR
This can be because you're sending invalid JSON.
Your code might look like
res.end();
One of the pitfalls is that returned data that is not a JSON but just a plain text payload regardless of headers set. I.e. sending out in Express via something like
res.send({a: "b"});
rather than
res.json({a: "b"});
would return this confusing error. Not easy to detect in network activity as it looks quite legit.
For someone looking here later. I received this error not because of my headers but because I was not recursively appending the response body to a string to JSON.parse later.
As per the MDN example (I've taken out some parts of their example not immediately relevant):
reader.read().then(function processText({ done, value }) {
if (done) {
console.log("Stream complete");
return;
}
result += chunk;
return reader.read().then(processText);
});
For my issue I had to
Use a named function (not an anonymous ()=>{}) inside the .then
Append the result together recursively.
Once done is true execute something else on the total appended result
Just in case this is helpful for you in the future and your issue is not header related, but related to the done value not being true with the initial JSON stream response.
I know this question has already been answered but just thought I add my thoughts.
This will happen when your response body is empty and response.json() is expecting a JSON string. Make sure that your API is returning a response body in JSON format if must be.