Relative path in Ajax works differently in different environment - javascript

It is a SpringBoot website. The html page url is http://xxxxx/trex/index/ And javascript code segment in index page as below
$(function(){
jQuery.ajax({
contentType:'application/json;charset=UTF-8',
type: "POST",
url: "getSignTypes",
cache: false,
dataType: "json",
success:function(data){
if(data !== 'NA'){
console.log(data);
$('#signType').combobox({
valueField:'id',
textField:'title',
editable:false,
data:data,
value:data[0].id
});
}
},
error:function(msg){
console.log(msg)
}
});
})
You can see I use relative path in url parameter of this ajax request. I guess since it is relative url, it should be converted into http://xxxxx/trex/index/getSignTypes. I test it in my local, and yes, it is as expected http://localhost:8088/trex/index/getSignTypes.
But when I deploy it to UAT, I find that the url is converted to http://hswcfc-trainexp-web.uat.homecreditcfc.cn/trex/getSignTypes. The index part is gone.
Why relative path in Ajax works differently in different environment? The ajax code is exactly the same. Any clue I can trace to find the difference? Thanks.
I past the UAT screen shot here.

A HTTP URL consists of several parts: protocol, hostname, port, username, password, path, query string (?....) and fragment (#....).
As suspected, your URL path ends in / in dev, but not in UAT. Think of it as "directories": /trex/index/ is the empty file name in /trex/index directory, while /trex/index is the file index in /trex directory. Web servers often treat the two the same way, but clients do not: when you do a relative path from there, you get /trex/index/getSignTypes in the first case, but /trex/getSignTypes in the second.
This is usually fixed by creating a redirect rule so that you can never accidentally write the same URL in two different ways (e.g. by redirect /trex/index to /trex/index/).

Related

How to get data from local JSON using Ajax?

Hello brilliant people!
I've been sitting hours trying to figure out why I cant load a local JSON file using Ajax. I bet it's some silly typo, of that I totally misunderstand something. I'm using Node.js Express.
The location of the two files:
"trollytrains/views/trips.ejs" (Doing the ajax-request)
"trollytrains/json/allstops.json"
$.ajax(
{
type: "GET",
url: "../json/allstops.json",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert('success');
},
error: function (msg) {
alert("error");
alert(msg.responseText);
}
});
I have tried altering the URL in all kinds of variations:
./allstops.json
allstops.json
json/allstops
/json/allstops
/json.allstops.json
No matter what I type I get a 404 error.
GET http://localhost:1337/json/allstops.json 404 (Not Found) jquery.min.js:4
Am I entering the wrong URL, or is there some other problem in my code that I haven't detected? I'm very new to JSON and Javascript so I wouln't be surprised.
I'd really appreciate some tips!
Best
/ J
Am I entering the wrong URL, or is there some other problem in my code that I haven't detected?
It depends on whether you can access the URL in the request in your example:
GET http://localhost:1337/json/allstops.json 404 (Not Found) jquery.min.js:4
See if you see the correct JSON when you go to http://localhost:1337/json/allstops.json with the browser. If you get 404 then this JSON is not served at this PATH and the problem can be either your backend failing to serve the JSON or you using the wrong URL.
It's impossible to tell you if you backend code is fine if you didn't include even a single line of the code that actually attempts to serve the JSON in question.
My assumption would be that you're not serving the JSON files.
I assume that you entire app is located in trollytrains directory and you have a json directory inside. To serve what's there you need to use something like this if you're using Express:
app.use('/json', express.static(path.join(__dirname, 'json')));
For more options to serve static files with and without Express, see this answer:
How to serve an image using nodejs
Try this.
$.ajax({
url: '../json/allstops.json',
dataType: 'json',
data:
async: false,
success:function()
{}
});

Wikipedia API. File not found Error

I'm trying to make a wikipedia search bar. The idea is to send a new AJAX request every time search input is changed. I'm using https://www.mediawiki.org/wiki/API:Search_and_discovery as a guideline.
var search = $('#search');
search.keyup(function() {
if (search.val() === '') {
result.html('');
}
$.ajax({
url: '//en.wikipedia.org/w/api.php',
data: {
action: 'query',
list: 'search',
format: 'json',
srsearch: search.val()
},
dataType: 'jsonp',
success: function(response) {
console.log("success!");
}
});
});
However, success function is not even triggered.
On any keypress the error I get is this ("d" pressed):
jquery-2.1.1.min.js:4 GET file://en.wikipedia.org/w/api.php?>callback=jQuery21107844703783826772_1484403407494&action=query&list=search&srse>arch=d&format=json&_=1484403407495 net::ERR_FILE_NOT_FOUND
Thank you in advance for any help or guidance!
Well, you're probably trying to do a AJAX request without a local server (opening your file directly in the browser).
First of all, your url options starts with //en... (without the protocol). It indicates that it'll construct your full url using the same protocol you're using. In this case: file://. That's because your browser is trying to reach file://en.wikipedia.org/....
So, you can set your url to https://en.wikipedia.org/w/api.php to make it work.
Just replace:
url: '//en.wikipedia.org/w/api.php',
with:
url: 'https://en.wikipedia.org/w/api.php',
Looks like you're running it from a simple html file located in your filesystem, in other words not running it from a web server (even local).
Try calling the api with
url: 'https://en.wikipedia.org/w/api.php'
or run the file from a web server (can be a local one).

Get proper root in javascript file

I'm having a problem with resolving the root of a URL between my local machine and after deploying an application on IIS to our dev server.
The url when running locally is something like this.
http://localhost:57173/
the url when running on the dev server is something like this.
http://ServerName/AppName
I have JQuery Ajax calls to a web api and it won't find the location on the dev server if the trailing slash is left off.
Here's the call
$.ajax({
type: "GET",
url: "api/MyApi/Get",
data: { period: selectedPeriod },
cache: false,
success: function (data) {
}
});
If I look in FireBug at the api call on the dev server, with the trailing slash left off, it will show
http://ServerName/api/MyApi/Get
If I do have the trailing slash, it will resolve correctly to this. (Notice the AppName now included.)
http://ServerName/AppName/api/MyApi/Get
What am I missing here? It looks like it's not finding the proper root of the application when I move it to this server. The trailing slash makes no difference locally. It will find the api either way. Any ideas how to resolve this?
I also had this issue, the way to solved it was declare a javascript variable that contains the part of the url that differs in both environments (dev and local) and prepend that to every ajax request:
I put that variable in the layout file (Views/Shared/_Layout.cshtml), so that it could be automatically filled by ASP.NET and then used globally (make sure to create the script before the #RenderSection call):
...
<script>
var baseUrl = #Html.Raw(Json.Encode(Url.Content("~")));
</sctipt>
#RenderSection("scripts", required: false)
</body>
...
Then prepend that variable in the url of the ajax call (for example View/Home/Index.cshtml):
#section scripts {
$.ajax({
type: "GET",
url: baseUrl + "api/MyApi/Get",
data: { period: selectedPeriod },
cache: false,
success: function (data) {}
});
}
A url without a leading slash is considered a relative url. Your url "api/MyApi/Get" will be resolved by the browser relative to the url of the page containing the script.
http://ServerName/AppName appears to the browser as if it is a page request, with AppName being the name of the page and the AppName is not considered when resolving the url.
http://ServerName/AppName/ (trailing slash) appears to the browser as a directory request and becomes the base of your relative url.
The best fix for this is probably to redirect requests for http://ServerName/AppName to http://ServerName/AppName/
To do the redirect from within your application, insert the following into your /Home/Index controller action (before any other code)
if (!Request.Url.AbsolutePath.EndsWith("/"))
{
return Redirect("~/");
}
This will redirect any request for http://ServerName/AppName to http://ServerName/AppName/ As a side effect, it would also redirect any requests for http://ServerName/AppName/Index to http://ServerName/AppName/ but I don't think that would cause you any problems.
Javascript typically doesn't run unless the user causes an event to occur. I prefer to use the following because it allows MVC to get the exact route properly everytime no matter where you deploy.
Html
<button data-url="#Url.Action("MyApi", "Get")"></button>
Javascript
$(document).ready(function()
{
$('button').on('click', function()
{
var url = $(this).data('url');
$.ajax({
type: "GET",
url: url,
data: { period: selectedPeriod },
cache: false,
success: function (data) {
});
});
});
Hard coding a url in javascript I consider bad-practice.

Ajax request to current path requests `text/html` instead of `application/json`

I have two almost identical JQuery requests that I issue after the page loads, the first one requests json for the current path and the second for a different url. I was surprised to see, though, that the first request type is text/html and the second is application/json. I would have expected both to be application/json. The requests look something like this:
$.ajax({
url: window.location.pathname,
type: 'GET',
dataType: 'json',
success: doSomething
});
$.ajax({
url: '/tags',
type: 'GET',
dataType: 'json',
success: doSomethingElse
});
Yet in the network tab I'm seeing:
What am I missing?
dataType: 'json' has two main effects:
It causes jQuery to ignore the content-type of the document it gets back from the server and to treat it as JSON regardless
It sets an Accept header (for HTTP content negotiation) requesting JSON
The server may use HTTP content negotiation to decide what to put in the response if it has different representations of the content in different formats. Most servers do not.
It looks like yours does not. It will always return HTML for the first URL and always return JSON for the second URL.
If you want your server to pay attention to the Accept header, then you have to configure it to do so (as well as providing a JSON version of the document as well as the HTML version).
The content type shown is the type of the response the server is sending you, not the type of request you are sending to the server.

Path for jquery ajax for reading a json file

I use this to read a json file stored on my server:
$.ajax({
type:"GET",
url:path,
contentType:"application/json; charset=UTF-8",
dataType:"json"
success:function(response)
{
console.log(response);
//stuff...
}
});
I have tried specifying the path as MyProject/build/web/leaflet/temp/xyz.json and as build/web/leaflet/xyz.json.
In both the cases I get a response of 404.
I have tried with both paths using $.getJSON,I find that the error occurs when the readyState of the XMLHttpRequest is 1.
How should I specify the path for getting the json file?
A relative URI in JS in the browser needs to be relative to the HTML document that is hosting the JavaScript.
Add / before your path and have a try.
ex: /MyProject/build/web/leaflet/temp/xyz.json or /build/web/leaflet/xyz.json

Categories

Resources