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.
Related
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>
Having a react frontend with my own expressjs api backend.
Express v. 4.16.0
Using fetch on the react frontend to get data works just fine.
fetch('/desResData')
.then(res => {....}
As soon as I try to post some data with the request I get: "POST http://localhost:3000/desResData 404 (Not Found)"
Code:
fetch('/desResData',
{
method: 'POST',
body: { product: "test" }, // tried JSON.stringify as well
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
}
)
.then(res => {....}
Roughly spoken I can have static communication from front to backend but I cant parametrize my requests.
ExpressJS:
router.get('/', async function (req, res, next) {
console.log(req.body) // tried with using req and without using it
findByProduct("product") // some async db operation // this part is working fine while fetching without any post parameters
.then(data => {
res.json()
})
You have to write router.post (not router.get) to process an HTTP POST request.
Notice the method of your fetch is POST. But you wrote router.get which handles a request where the method is GET.
If a POST request comes in for a route that doesn't exist, express will give 404. This applies even if there is a GET handler for the same route.
(Hint: you can have separate GET, POST, PUT, DELETE, etc. handlers for the same route by using .get, .post, .put, .delete, etc.)
add this in your server code :
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS, HEAD');
next();
});
inside package.json of your react code :
"proxy": "http://localhost:serverport", <-- server port will be port of your node-express server
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
I'm having a problem getting the cookie with my auth token to pass as part of my requests. When I look in Chrome after my authentication request is fulfilled, the response cookie is appropriately set, but it is never passed into additional requests.
Express route for /login that generates the cookie:
router.get('/login',
passport.authenticate('local', {
session: false
}),
function(req, res) {
console.log('/login authentication successful');
token.generate(req.users, function(result) {
res.cookie('access_token', result, {
//secure : true,
//maxAge : 1000*60*60, // 1 hour
path: '/',
httpOnly: true
});
res.json(Response.success(req.user));
});
}
);
I also have the following for setting the headers:
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Credentials", true);
next();
});
Now in Angular, I am passing a config object to my $http request with withCredentials: true, but so far, nothing has worked.
$http({
method: 'GET',
url: 'http://localhost:3000/api/v1/devices',
withCredentials: true
}).then(function successCallback(response) {
// do stuff
}, function errorCallback(response) {
// oh noes!
});
A note about my setup: I have one node server running to provide the backend on port 3000, with another node server using browserSync to display the clientside on port 8080. I've seen a suggestion that using http://localhost:8080 instead of an IP could cause the cookie to not get passed, but that doesn't appear to make a difference.
Hopefully one of you fine guys or gals will have an inkling as to what my problem is. Thanks!
seem to be missing header for Access-Control-Allow-Methods which would include verbs used "OPTIONS,POST,GET,PUT,DELETE" etc
Reference MDN HTTP access control (CORS)
I don't use node a lot for cors but I know there are packages that will do all this for you
I am trying to hit an https based API, which is successfully working in POSTMAN and other REST client, but not in my AngularJS app.
Following is the code -
var req = {
method: 'POST',
url: 'https://agXXXXX.com/api/contact/',
headers: {
'Content-Type': undefined
},
data: user,
withCredentials: true
};
$http(req)
.then(function(data){
console.log("--Data--");
console.log(data);
})
After following few stack CORS related article, I also included this in .config(), but no luck -
$httpProvider.defaults.useXDomain = true;
$httpProvider.defaults.headers.common = {Accept: "application/json, text/plain, */*"};
$httpProvider.defaults.headers.post = {"Content-Type": "application/json;charset=utf-8"};
Following is the error I am facing -
Let me know what I am doing wrong, or missing here.
If you just need test your app you can use this chrome plugin:
https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi
But if you need this in production, you need config your server. If you are using SPRING:
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST,PUT, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Headers", "Authorization,Content-Type");
chain.doFilter(req, res);
You should add in your server code headers to enable cors.
in this site you could read about it, and get code to implement it depending on the language in your backend:
http://enable-cors.org/