Response from pre-flight failing with Status 405 - javascript

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...

Related

cURL command to Axios request with json data

I've got this cURL request working perfectly on remote interface just as it should
curl -XGET "https://server.host:8080/peregrine" -d '{"exchanges":["kucoin", "kraken"],"volume":10}' -k
I'm trying to build a little frontend app with Vue.js and need the above converted to an Axios get request.
I've been trying the following so far:
axios({
method: 'get',
url: 'https://server.host/peregrine',
data: {"exchanges":["kucoin", "kraken"],"volume":10}
});
putting params instead of data makes it a URL and remote server says that it received no data.
What am I doing wrong? Thanks.
Likely the problem could be that using GET you cannot pass data like you are doing. You have to pass them as query parameter.
Try to change your call with:
axios.get('https://server.host/peregrine', {
params: {"exchanges":["kucoin", "kraken"],"volume":10}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.then(function () {
// always executed
});
GET requests should not have request bodies.
CURL will allow you to make a GET request with one, but XMLHttpRequest and fetch (the HTTP APIs in browsers which axios wraps) will not.
Make a POST request instead. You might need to change the server-side code to support this.
Thanks for your replies!
Indeed there's no way to send data body with axios.get()
We ended up tuning the server side to accept normal generic GET requests. Thanks again to everyone who answered!

How to set username and password in axios get method header

I want to fetch some data from a server via axios in my react project. When i put the url on browser and hit enter browser ask me username and password and after that, i can see the json data. But i dont know how to set the password and username in axios header in a get method. I have searched it in many forums and pages,especially this link didin't help me: Sending axios get request with authorization header . So finally i tried (many things before this, but i was more confused):
componentDidMount() {
axios.get('http://my_url/api/stb', {auth: {
username: 'usrnm',
password: 'pswrd'
}})
.then(function(response) {
console.log(response.data);
console.log(response.headers['Authorization']);
}).catch(err => console.log(err));
}
And i can not get anything. I get this error in console:
Error: Network Error
Stack trace:
createError#http://localhost:3000/static/js/bundle.js:2195:15
handleError#http://localhost:3000/static/js/bundle.js:1724:14
Actually, the api documentation mentioned that with these words:
If there is no header or not correct data - server's answer will
contain HTTP status 401 Unauthorized and message:
< {"status":"ERROR","results":"","error":"401 Unauthorized request"}
For successful authentification is sufficient to add in every request
header to the API:
Authorization: Basic <base64encode("login":"password")>
The weird thing is, when i use postman, the response send me a "401 unauthorized" response below the body section. But i can not see any 401 errors in browser's console.
Ok i found the solution. As i mentioned in the comments that i wrote for my question, there was a cors problem also. And i figured out that cors problem was appearing because of that i can not authorize correctly. So cors is a nature result of my question. Whatever.. I want to share my solution and i hope it helps another people because i couldent find a clear authorization example with react and axios.
I installed base-64 library via npm and:
componentDidMount() {
const tok = 'my_username:my_password';
const hash = Base64.encode(tok);
const Basic = 'Basic ' + hash;
axios.get('http://my_url/api/stb', {headers : { 'Authorization' : Basic }})
.then(function(response) {
console.log(response.data);
console.log(response.headers['Authorization']);
}).catch(err => console.log(err));
}
And dont forget to get Authorization in single quotes and dont struggle for hours like me :)

Uncaught (in promise) SyntaxError: Unexpected end of JSON input

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.

How to handle 302 in angular 2

I am getting error with status 302
But while trying to log error in catch I am getting 200
post(url, data, successCallBack, errCallback) {
return this.http.post(apiDomain + url, JSON.stringify(data), {
headers: this.headers
}).catch(this.handleError).subscribe(
(res) => {
successCallBack(res.json());
},
(err) => {
errCallback(err);
}
);
}
private handleError(error: any) {
let errMsg = (error.message) ? error.message :
error.status;
console.log(error.status); // log is 200
console.log(error)
console.error(errMsg);
return Observable.throw(errMsg);
}
Requirement I want to send another post call on redirect URL redirects.
How to get Redirect URL.
Need help.
Late answer I know, but for anyone stumbling across this.
The short answer is you can't as the browser handles 302's itself and won't tell angular anything about that. What you can do is set-up an interceptor style class that monitors what is going on.
Google for angular2 http interceptor or similar, it's a little beefier than your example above and can monitor every XHR connection. An example is here:
https://www.illucit.com/blog/2016/03/angular2-http-authentication-interceptor/
What this now allows is that any connection will come through your interceptor. As we won't be able to monitor 302s, we have to think about what might happen. For example in my example the request suddenly changes the url to something with my auth in it.
Great so my 1st bit of pseudo code would be:
if (response.url.contains('my-auth string')) {
redirect....
}
I can also see on the headers provided that instead of application/json I've suddenly gone to text/html. Hmm, that's another change I can check for:
if (response.url.contains('my-auth string') && response.headers['content-type'] == 'text/html') {
redirect....
}
You may have other parameters you can check, however these were good enough to detect a redirect for me. Admittedly this is with respect to being redirected to login and not another example, hopefully you get enough distinct changes check for you to decide whether you have got a 302.

Prevent JavaScript from breaking with a 403 HTTP response

I'm grabbing user information from the Last.fm website with a JQuery $.get request.
Since some users' accounts are private, I sometimes receive a 403 error stating that authentication is required. This breaks the JS code. The last.fm API doesn't let you see if a user is private or not.
Is there a way to catch this error and continue through the code?
Thanks!
Not sure if it works with cross-domain requests, but you could do something like this:
$.ajax({
type: 'GET',
statusCode: {
403: function() {
alert('a 403 was received');
}
},
success: function() {
alert('everything OK');
}
});
Or possibly set it up in $.ajaxSetup() if it works ?
You would be better using a proxy to get the data from API since $.ajax() error handler won;t return errors for cross domain requests per jQery API docs:
http://api.jquery.com/jQuery.ajax/
EDIT Note in docs for error option:
"Note: This handler is not called for cross-domain script and JSONP requests."

Categories