I am trying to fetch local api made in asp.net api which is running in https://localhost:44388/. When I tried to fetch get request it responds ok but return html not json. The problem might occur by two reasons:
1.typo in url (But I checked in my browser, it worked)
2.Server restart needed
What might be the problem with my code?
componentDidMount(){
var proxyUrl = "http://127.0.0.1:3000/";
var targetUrl = "https://127.0.0.1:44388/api/product/getproducts";
fetch(proxyUrl+targetUrl, {
method:'GET',
headers:{
'Access-Control-Allow-Origin':'*',
'Access-Control-Allow-Mehods': '*',
'Access-Control-Allow-Headers': '*',
'Access-Control-Allow-Credentials':'*',
'Content-type':'application/json'
}
})
.then(data=>{
if(!data.ok){
throw new Error("Error");
}else{
return data.json();
}
})
.then(data=>this.setState({products:data}))
}
when you give parameter as:proxyUrl+targetUrl,
actually the url which you have called is :
http://127.0.0.1:3000/https://127.0.0.1:44388/api/product/getproducts
which does not seems to be correct.
i think the structure of url you'v given to fetch function is wrong.
Related
I'm trying to access this cookies (the response ones):
When I open the request in the chrome debug tools in the network section I can clearly see that the cookies are present, but how can I access those values from my code? I've never worked with cookies before and I don't know what to do to "extract" them... I'm working on a Ionic2 project using Http.
I've read that the allowCredentials: true header has to be sent but that didn't work...
Here's the request/response details:
Here's the service:
public callLogin(service_guid: string, pos_guid: string, login_data: Object) {
return this.http.post(
this.url + service_guid + "/" + pos_guid + "/ack",
login_data,
{withCredentials: true}
)
.map(response => response.headers);
}
And the caller:
this.__posService.callLogin(login_data.service_guid, login_data.pos_guid, {"password": data.password})
.subscribe(
res => {
console.log("Success:");
console.log(res.get("apsession"); // this returns undefined
},
err => {
console.log("Error:");
}
);
When I try to access the cookie from the header it returns undefined. What am I doing wrong here?
The name of the response header you are trying to get is actually Set-Cookie not apsession. So if you did something like res.get("set-cookie") it would return the first header that matched that name. Since you have more than 1, you could do:
let headers: Headers = res.headers;
headers.getAll('set-cookie');
which returns a list of all headers with that name. You could find apsession in there probably.
See:
https://angular.io/docs/ts/latest/api/http/index/Headers-class.html
https://developer.mozilla.org/en-US/docs/Web/API/Response/headers
https://developer.mozilla.org/en-US/docs/Web/API/Headers
Breeze is calling the "fail()" function, even though the data seems to be returned from the odata service (as well as being in the error object). There are 5 "transactions" returned from the ODATA service (as seen in Chrome developer tools) as well as in the "data" property of the error object being passed to the fail function.
Calling code looks like this:
function getTransactions() {
var query = breeze.EntityQuery.from("Transactions")
.take(5);
return entityManager.executeQuery(query,
function(data) {
log("transaction Query success!");
var transactions = data.results;
},
function(err) {
log("Query failed:" + err.message);
});
}
I am at a loss as to what is wrong that is causing the "fail()."
There IS a Transaction constructor defined, code below:
function registerTransactions(metadataStore) {
metadataStore.registerEntityTypeCtor('Transaction', Transaction);
// constructor -- empty
function Transaction() { };
Object.defineProperty(Transaction.prototype, 'itemCount', {
get: function () {
return 0;
}
});
}
Note the url for the odata resource is "Transactions" but the entity is Transaction. What are the reasons why the "Fail() function would be called?
Error.message = "; " which isn't helping much.
I believe I am on the latest Breeze 1.4.11 and datajs 1.1.2
After much research, I found the problem was another funcky CORS setting on the service side. I was able to figure it out by going directly to dataJS against the same service, and getting a more informative error message.
What you MUST do on the service side is something like this:
var cors = new EnableCorsAttribute("*", "*", "*", "DataServiceVersion, MaxDataServiceVersion");
The last parameter has to with the service sending the OData version in the header and thereby allowing the client to determine if it can handle the specified version of OData.
If anyone knows more details about this, feel free to comment.
I am trying to write an Integration test which calls my real service (that returns JSON) and makes sure the format of the JSON is OK.
I get an error
Error: Unable to load http://localhost:7200/users/signoff status: 0
ErrorCtor#http://localhost:9000/resources/www/tests/lib/dojo/errors/create.js:29
onError#http://localhost:9000/resources/www/tests/lib/dojo/request/xhr.js:133
I've got a service that has the actual functions to interact with the server and it returns promises from every function. My test looks like this.
define([
'intern!bdd',
'intern/chai!expect',
'app/services/myService'
], function (bdd, expect, MyService) {
with (bdd) {
describe('Service Tests', function () {
var service;
before(function () {
service = MyService.getInstance();
});
it('should sign user off', function(){
var dfd = this.async(2000);
service.signUserOff().then(dfd.callback(function (data) {
expect(data).to.exist;
expect(data.status).to.exist;
}), dfd.reject.bind(dfd));
});
});
}
});
service.signOff() makes a call to the real service and then returns a promise. I have tried this with Firefox and PhantomJS both and I keep getting this error. The weird thing is, the URL in the error works fine if loaded manually in the browser.
I wonder if this is something to do with Intern not being able to load the request/xhr.js and therefore throwing this error?
The request that you are making is considered a cross-site request, so you need to either make sure your server correctly responds with the appropriate CORS headers for such a request, or you need to set up a reverse proxy that ensures that the XHR requests are occurring through the same origin.
Currently, I use the built-in meteor http method (see http://docs.meteor.com/#http) for issuing http calls, on both my client and my server.
However, I'm experiencing two issues:
is it possible to cancel a request?
is it possible to have multiple query parameters which share the same key?
Are these just Meteor limitations, or are there ways to get both to work using Meteor?
I know I could you jquery on the clientside, and there must be a server-side solution which supports both as wel, but I'd prefer sticking with meteor code here.
"is it possible to cancel a request?"
HTTP.call() does not appear to return an object on which we could call something like a stop() method. Perhaps a solution would be to prevent execution of your callback based on a Session variable?
HTTP.call("GET", url, function(error, result) {
if (!Session.get("stopHTTP")) {
// Callback code here
}
});
Then when you reach a point where you want to cancel the request, do this:
Session.set("stopHTTP", true);
On the server, instead of Session perhaps you could use an environment variable?
Note that the HTTP.call() options object does accept a timeout key, so if you're just worried about the request never timing out, you can set this to whatever millisecond integer you want.
"is it possible to have multiple query parameters which share the same key?"
Yes, this appears to be possible. Here's a simple test I used:
Meteor code:
HTTP.call("GET", "http://localhost:1337", {
query: "id=foo&id=bar"
}, function(error, result) {
// ...
});
Separate Node.js server: (just the basic example on the Node.js homepage, with a console.log line to output the request URL with query string)
var http = require('http');
http.createServer(function(req, res) {
console.log(req.url); // Here I log the request URL, with the query string
res.writeHead(200, {
'Content-Type': 'text/plain'
});
res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
When the Meteor server is run, the Node.js server logged:
/?id=foo&id=bar
Of course, this is only for GET URL query parameters. If you need to do this for POST params, perhaps you could store the separate values as a serialized array string with EJSON.stringify?
When I try to call an external server for JSON queries in Meteor with the Meteor.http.call("GET") method I get the error message "not allowed by Access-Control-Allow-Origin".
How do I allow my meteor app to make HTTP calls to other servers?
Right now I run it on localhost.
The code I run is this:
Meteor.http.call("GET",
"http://api.vasttrafik.se/bin/rest.exe/v1/location.name?authKey=XXXX&format=json&jsonpCallback=processJSON&input=kungsportsplatsen",
function(error, result) {
console.log("test");
}
);
There are other questions similar to this on StackOverflow.
You're restricted by the server you're trying to connect to when you do this from the client side (AJAX).
One way to solve it is if you have access to the external server, you can modify the header file to allow some, or all origins by:
Access-Control-Allow-Origin: *
However, if you place the call on the server side and not provide a callback function, the call will be made synchronously, thus not with AJAX, and it should succeed.
Here's
Meteor.methods({checkTwitter: function (userId) {
this.unblock();
var result = Meteor.http.call("GET", "http://api.twitter.com/xyz", {params: {user: userId}});
if (result.statusCode === 200) return true
return false;
}});