0

I've worked on the Tour of Heroes tutorial,works perfectly well.

I've made a Web api with C# as a small backend to test further. When I try to join said back-end, angular returns an error 404 not found, even when next tab is on the exact same road.

This is the error :

 An error occurred Object { _body: Object, status: 404, ok: false, statusText: "Not Found", headers: Object, type: null, url: "http://localhost:58225/api/Character" }

I've tried login the answer of the call, I return an "[object Object]" , but I guess that's the error message itself.

@Injectable()
export class CharacterService{
private charactersUrl = 'http://localhost:58225/api/Character';

constructor(private http:Http){}

getCharacters(): Promise<Character[]>{
    alert("Getting Characters");

    var my_data = this.http.get(this.charactersUrl)
                    .toPromise()
                    .then(response => response.json().data)

    console.log("Resultat de l'appel = "+my_data);

    return this.http.get(this.charactersUrl)
        .toPromise()
        .then( (response => response.json().data as Character[]) )
        .catch(this.handleError);
}

As you can see there's nothing really original here.

The /api/Character returns an IEnumerable that contains the list of my characters.

public IEnumerable<string> GetAll()
    {
        List<Character> myCharacs = repo.Get().ToList();
        List<String> myJsonCharacs = new List<string>();
        foreach (var charac in myCharacs)
        {
            var cur = jsonConverter.Serialize(charac);
            myJsonCharacs.Add(cur);
        }

        return myJsonCharacs;

    }

I don't really know how I'm supposed to test further ? I'm reading on promises and observables to see if I missed something, but this is the simplest example I could think of :/

Edit :

I have changed the response of the API for json by following this : How do I get ASP.NET Web API to return JSON instead of XML using Chrome?.

The API now returns this when I browse directly to it :

 ["{\"characterName\":\"Azazel\",\"playerName\":\"Mulhouse\",\"game\":{\"name\":\"Call of Cthulhu\",\"BaseAttributes\":[{\"max\":18,\"value\":12,\"name\":\"appearance\"},{\"max\":18,\"value\":21,\"name\":\"constitution\"},{\"max\":18,\"value\":19,\"name\":\"strength\"},{\"max\":18,\"value\":17,\"name\":\"dexterity\"},{\"max\":18,\"value\":15,\"name\":\"power\"},{\"max\":18,\"value\":13,\"name\":\"size\"},{\"max\":18,\"value\":13,\"name\":\"intelligence\"},{\"max\":24,\"value\":12,\"name\":\"education\"}],.....

Made no difference. (This is a sample of the answer, it's actually way longer)

Also, since the answer is a 404 to the path, I suspect the problem is not related to the format of the answer but more to angular's configuration. How could I check this?

EDIT : Could a difference between the structure of my objects cause this 404 error? If my json character coming from the server has more fields than the json character defined in angular2, what happens?

Thank you

Community
  • 1
  • 1
DoctorPrisme
  • 103
  • 2
  • 11
  • What happens when you go with the browser directly to [http://localhost:58225/api/Character](http://localhost:58225/api/Character) – Poul Kruijt Feb 20 '17 at 11:12
  • Could it be, that perhaps should use just `response.json()` instead of `response.json().data`?? – AT82 Feb 20 '17 at 11:12
  • first of all, setup your c# web-api to return JSON! – slaesh Feb 20 '17 at 11:13
  • @mxii I'll try, but the error message indicates that it can't find the road... and the response.json() normally converts the answer to json, doesn't it? – DoctorPrisme Feb 20 '17 at 11:15
  • @PierreDuc I see the "array of string" answer. – DoctorPrisme Feb 20 '17 at 11:16
  • @AJT_82 I did that, no difference. – DoctorPrisme Feb 20 '17 at 11:17
  • @DoctorPrisme Yes, that was just a wild guess, when not knowing how the response looks like. and as to your comment that *response.json() normally converts the answer to json, doesn't it?*. No it doesn't, you need to send a JSON string to be able to extract the data. Could you post how your response looks like in your question? – AT82 Feb 20 '17 at 11:20
  • 1
    `response.json()` will convert the JSON-STRING-response into a object !! – slaesh Feb 20 '17 at 11:23
  • 1. if you browse with your browser to that road, you MUST see a JSON string. 2. is it accessible via browser? check spelling or anything else of your road.. – slaesh Feb 20 '17 at 11:25
  • @AJT_82 I did. When I browse to localhost:58225/api/character is the .... containing the characters as json. I've just added in web api config these lines : config.Formatters.JsonFormatter.SupportedMediaTypes .Add(new MediaTypeHeaderValue("text/html") ); (as per http://stackoverflow.com/questions/9847564/how-do-i-get-asp-net-web-api-to-return-json-instead-of-xml-using-chrome ) This changed my answer to : ["{\"characterName\":\"Azazel\",\"playerName\":\"Mulhouse\", (I spare you the end of it cause each object is quite long). I receive the same error. – DoctorPrisme Feb 20 '17 at 11:26
  • 3. `response.json().data` will only work if there is a `data` property on your received JSON – slaesh Feb 20 '17 at 11:26

2 Answers2

0
  • The WWW is case-sensitive!
private charactersUrl = 'http://localhost:58225/api/character';
  • your server should response just a JSON-string

  • seems like there is no data property, so use it like this:

.then( (response => response.json() as Character[]) )
  • change your server function like this (serialize to json yourself!)
public string GetAll()
{
    List<Character> myCharacs = repo.Get().ToArray();
    return jsonConverter.Serialize(myCharacs);
}
  • or let the framework do the work..
public IEnumerable<Character> GetAll()
{
    List<Character> myCharacs = repo.Get().ToArray();
    return myCharacs;
}
slaesh
  • 16,659
  • 6
  • 50
  • 52
  • The API url case is correct in my code, I don't know why the copy-paste gave a lowercase. My server now gives a JSON string as response. I've tried using "response => response.Json as Character[]) Nothing changed. – DoctorPrisme Feb 20 '17 at 11:31
  • If you can access the route via browser, there should be no reason that angular cant! and the error 404 is given by the server, not from angular. – slaesh Feb 20 '17 at 12:02
  • Well... I agree on the fact there is no reason angular can't. But still.... – DoctorPrisme Feb 20 '17 at 12:05
  • Can't say much more from here.. Check another tool like `Postman` to `GET` that route. The http module don't cares about object structures.. it just get the http-response.. – slaesh Feb 20 '17 at 12:08
  • If I click on the link provided in the error message, I see the objects in my browser :3 – DoctorPrisme Feb 20 '17 at 12:10
  • is there a special reason to use Promises instead of Observables? change this `this.http.get(this.charactersUrl).toPromise().then` to this `this.http.get(this.charactersUrl).map(` and `.subscribe` your `getCharacters()` function. – slaesh Feb 20 '17 at 12:11
  • any logs or exceptions on your server side if angular tries to connect? – slaesh Feb 20 '17 at 12:14
  • doesnt matter for communication, but see my updated answer for server-side function. – slaesh Feb 20 '17 at 12:18
  • I don't get what you mean about the server. The getall method already return json, it's already converted via jsonconverter.serialize too. And the use of promise or observable is certainly not responsible for the connection to backend... – DoctorPrisme Feb 20 '17 at 12:47
  • Regarding Promise/Observable .. thats right, should affect! – slaesh Feb 20 '17 at 12:49
  • Regarding your JSON, its not a valid JSON resposnse.. it's mixing serialization of yourself and framework.. what your are returning is a list of serialized objects which the framework will serialize again. – slaesh Feb 20 '17 at 12:50
  • but shouldn't affect the connection in anyway.. the `.json()` would throw an error if it will arrive your angular. :) can't help from here.. i guess you should debug your server.. dont see any angular error here ! – slaesh Feb 20 '17 at 12:52
  • Yes, my api gives an object that has other nested object. These are serialized to json, tough. What should I change, – DoctorPrisme Feb 20 '17 at 12:52
  • change as shown in my answer.. try to `JSON.parse(..)` your output on your chrome debug console.. it will throw an error.. – slaesh Feb 20 '17 at 12:53
  • Normally server would reponse with a better error-message pointing to the CORS problem, damn! – slaesh Feb 20 '17 at 12:55
  • What changed? Debugging server without any exceptions? Are you seeing an incoming connection during server debugging? – slaesh Feb 20 '17 at 14:28
  • I've tried connecting to the server with postman : no problem, however I can't see any CORS header. It looks like CORS isn't "turned on", even after I installed nuget package and changed the config. – DoctorPrisme Feb 20 '17 at 14:49
0

A friend finally found the answer :

REMOVE THE IN-MEMORY-DATA-SERVICE references. That thing blocks http requests.

I know have a different error, but at least I can reach the API.

DoctorPrisme
  • 103
  • 2
  • 11