I would like to make a Javascript post request to a server but i would like to make it though a local file. I just want to send a form and that's it, i only need to know import is successful. I used fetch, but i always got 401 response from the server eventhough i use the valid Authorization credentials. As far as i know i have to send the Authorization in header, is there any way to to it? I can't pass the preflight because i need to do the request in local file.
<script type="text/javascript" language="javascript">
var data1 = {id:"aC4yMsejvnc8W8EAjbc2on",submission:{code:"xxx",name: "Oxx2",phone:"OBB",type:"aas",partner:"xx",meta: {instanceID: "uuid:8992c3c2-3418-4ba9-a8e2-b00e03ea36b6"}}};
async function Kobotest(url="",data={}) {
const response = await fetch(url,{
method: "POST",
mode:"no-cors",
cache:"no-cache",
headers: {
'Access-Control-Allow-Origin':'https://kc.humanitarianresponse.info/api/v1/submissions.json',
'Access-Control-Allow-Headers':"X-Requested-With, Content-Type, Accept, Origin, Authorization",
'Access-Control-Allow-Methods':"GET, POST, PUT, DELETE, OPTIONS",
"Authorization": "Token 36f1e3b2c7b7a27eca929xxxxxxxxxxxxxxxxxxx",
'Content-Type':"application/json"
},
redirect:"follow",
})};
Kobotest("https://kc.humanitarianresponse.info/api/v1/submissions.json", data = data1)
.then ((data) => {
console.log(data);
});
</script>
Related
please help me. this not working. after call this method sms send properly but showing error this (failed)net::ERR_FAILED)
function sendSms(passWord, userName, smsRate, mType, MsgType) {
var getMessage = $('.composeSMS').val(),
number = '88'+$('[name="tags-input"]').val();
var convateMessage = setConvertedMessage(getMessage);
$.ajax({
type: 'get',
url: 'https://api.example.com:8443/sms/sms?',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Access-Control-Allow-Credentials': true,
'Access-Control-Allow-Headers': '*',
'Access-Control-Allow-Methods': 'GET, PUT, POST, DELETE, HEAD, OPTIONS, PATCH',
'Access-Control-Allow-Origin': '*',
'Access-Control-Expose-Headers': '*',
'Allow': 'GET, HEAD, POST, TRACE, OPTIONS',
},
data: { source: mType, username: userName, password: passWord, type: 2, destination: number, message: convateMessage,format: "json"
},
success: function( data ) {
conosle.log(data);
},
});
}
Error screenshort
CORS is not controlled by the consumer (the client browser) but by the provider (the cross origin server you are connecting to. CORS was introduced for security reasons, and there'd be no point if adding some headers completely disabled a servers ability to circumvent this security measure.
First thing to remove is the Access-Control-* headers from your request. These are response headers, and adding them to a request can result in otherwise functioning cross origin requests to fail - don't worry, this is a rookie mistake, you'll see this on stack overflow daily at least!
adding most headers will trigger an OPTIONS pre-flight check - which will fail if the server isn't expecting such a request
If, after you've made your your request is correct and has no extra (unexpected) headers in it, the request still fails, check the response headers - if there is no Access-Control-Allow-Origin in the response headers, then the server you are accessing does not allow browsers to make such a request
The solution then is to make the request from your own server, using server side code
As you have not mentioned anything about your server, let me try to help using some pseudo code
On the server you'd have something like
handle '/sms'
incoming parameters: source, username, password, type, destination, message, format
response = get(url { source, username, password, type, destination, message, format})
return response to client
In a nodeJs app, i am sending multipart/form-data to the server via ajax request. I am also using csurf package to guard against csrf attacks
Problem
When i submit my form without ajax request, everything works fine but when i submit my form using ajax request, i get invalid csrf token error on the server.
As far as i have understood the cause of this error, its because of cookies not sent with the request.
To send the cookies with ajax request, i set credentials: 'same-origin' in the post request made via fetch api but that didn't fix the issue. I also tried setting credentials: 'include' but that didn't make any difference.
Question
Is my understanding correct that this issue is because of cookies not being sent with ajax request and how can i fix this issue?
Code
let response = await fetch(requestUrl, {
method: 'POST',
credentials: 'include',
headers: {
'Content-Type': 'multiplart/form-data'
},
body: new URLSearchParams(form)
});
When using fetch()/AJAX with csurf, you need to pass the CSRF token as a request header:
// Read the CSRF token from a hidden input in the form
const token = document.querySelector('input[name="csrf-token"]').value;
// POST using the Fetch API
fetch('/<route.name>', {
headers: {
// pass the csrf token as a header
'CSRF-Token': token
},
method: 'POST',
body: {
...
}
});
I have an node js API.
app.post('/myapi', function (req, res) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, X-Request-With");
res.header("Content-Type", "application/json");
res.header("Accept", "application/json");
* do something *
res.json({ api : "api called successfully" });
});
I have a html code placed in the public folder. I am using express to run both the html code and backend APIs.
My html code has request fetch as,
var headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Accept', 'application/json, text/plain, */*');
var options = {
method: 'POST',
body: JSON.stringify(loginDetails),
headers: headers,
mode: 'no-cors'
};
fetch('http://localhost:3001/myapi', options)
.then(function (response) {
console.log(response);
res=response.statusCode;
// return response
if (res==0) {
window.location.assign("http://localhost:3001/home.html");
}
});
When I run the code in browser. When I click on a button that calls the above frontend code. It sends two request. Both the call fails. One is localhost request which is document call and other is the API call. But there is no response in the API call.
I was getting response in UI from the / call,
cannot POST/
So I tried adding following code,
app.post('/', function (req, res) {
res.json({ "status": "successfull" });
});
Now also there is two calls but UI returns {status : successfull} (output of /). But it is not returning output of /myapi.
Can someone please help?
I am getting an infinity initiator for localhost document. See the screenshot.
Append any unique parameter to request to avoid sending cached version of request.
/api/name?id=<unique_param>
You can find more details here and here.
I make $http POST request to a server api but request method changes to OPTIONS.
I do it all with localhost. So I did the same request through the Postman and everything works
Service:
function httpReg(userData) {
console.log(userData)
return $http({
method: 'POST',
url: CONFIG.APIHost + '/auth/signup',
data: {
"username": userData.username,
"email":userData.email,
"password": userData.password
},
headers: {
'Content-Type': 'application/json; charset=utf-8'
}
});
}
Screenshot:
(source: joxi.net)
Actually your preflight request is bounced back.
If the browser doesn't trusts the data source you are hitting the browser first sends a preflight request to that server and if that returns 200OK, then browser will send your original request.
The applies only to browsers, and other tools such as postman dosen't send and preflight requests, so your code might work their.
How to solve the problem.
Add headers for accepted options GET, POST, OPTIONS, PUT to the requested resource.
Yes it looks like cors problem.
Try one of the following:
Try to set the referrer in your header
Try this:
app.config(['$httpProvider', function ($httpProvider) {
//Reset headers to avoid OPTIONS request (aka preflight)
$httpProvider.defaults.headers.common = {};
$httpProvider.defaults.headers.post = {};
$httpProvider.defaults.headers.put = {};
$httpProvider.defaults.headers.patch = {};
}]);
Remove the x-auth* settings from _app.js file of your yeoman/gulp settings.
Reference: AngularJS performs an OPTIONS HTTP request for a cross-origin resource
I am trying to add a custom header, X-Query-Key, to a HTTP request using Fetch API or request but when I add this to the header of the request it appears to fail at setting the headers and the Request Method is set to OPTIONS for some reason.
When I remove the header it goes back to being GET as it should do.
Sample code looks like below:
const options = {
url: url,
headers: {
'Accept': 'application/json',
'X-Query-Key': '123456' //Adding this breaks the request
}
};
return request(options, (err, res, body) => {
console.log(body);
});
Try this:
const headers = new Headers({
"Accept": "application/json",
"X-Query-Key": "123456",
});
const options = {
url: url,
headers: headers
};
return request(options, (err, res, body) => {
console.log(body);
});
If that does not solve the issue, it may be related to CORS.
Custom headers on cross-origin requests must be supported by the
server from which the resource is requested. The server in this
example would need to be configured to accept the X-Custom-Header
header in order for the fetch to succeed. When a custom header is set,
the browser performs a preflight check. This means that the browser
first sends an OPTIONS request to the server to determine what HTTP
methods and headers are allowed by the server. If the server is
configured to accept the method and headers of the original request,
then it is sent. Otherwise, an error is thrown.
So you will have 2 requests if use custom headers, first one with method OPTIONS to check if server allows custom headers and after that if the server response is 200 OK and allows your originary request the second one will be send
Working with the Fetch API