Can someone elaborate on exactly what is being asked? - javascript

We're setting up a basic http web server using node. We're coding in Java Script if this helps. I don't understand exactly what is being asked of us. Windows using Gitbash.
"Return the file to the user by setting the correct Content-Type for the file and writing it to the response"
That is word for word what is asked in the lab.
If someone could explain I'd appreciate it.

Whenever someone makes a request to a server, the server answers the request with a header and a body. The body usually contains the data you see on the browser and the header contains information about the type of content the server is returning.
When the server returns a file, it has to set this information on the header, otherwise the browser would expect the content to be just text. This information on the header that describes the content is called Content-Type.
As pointed out by Elliott Frisch, this web page contains a list of the suported mime types that your server should be returning: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types

Basically it's a header sent in the request in addition to the request body. If you're sending say...video content to a server how is it supposed to know that from say an image?
There are several different kinds that can be seen here though usually you don't need content-type headers for things like POCOs, POJOs, and raw text. Here is a list of all the types
What are all the possible values for HTTP "Content-Type" header?
Here is how to change them in a fetch request from react (since you mentioned javascript):
fetch(url, {
method: "POST",
body: data,
headers: {
"Content-Type": "application/json"
},
credentials: "same-origin"
})
this would send a json data payload (you have to turn it into json manually) in a post request.
Also as an aside your post was tagged "java"....javascript and java are not the same thing.

Related

How to respond with HTML or JSON depending on the request in Sails.js

Let's say I have a model called User with its basic REST CRUD (GET, POST, DELETE, UPDATE).
When I go to user/4 (where 4 is an ID of a User that doesn't exist), there are two cases:
If I'm doing it with a REST client like Postman, I'd get a 404 and nothing else.
If I'm on the browser, I'll get a 404 page (with text, images, etc), which is defined in the views folder.
How can I achieve this for findOne, find, and other URLs? I want to be able to have JSON-only responses, and HTML pages responses for different types of requests. But I don't want to override the functions, because the ORM is already doing a lot of work that I don't want to lose.
EDIT: My solution would be to leave the API with a prefix, such as /api/user/4 and the HTML response without the prefix user/4, but I'd like to see more elegant solutions.
EDIT 2: I just decided to go all JSON, and use a REST service only with an independent front end ;)
If you have control over the headers sent by the API client, I see two clean semantic solutions, based on the headers sent :
you could rely on the X-Requested-With: XMLHttpRequest header to recognize Ajax queries
rely on a Accept: text/json header to explicitly request json
You could also modify the url with file extensions to request a specific response, user/4.html => send html, user/4 => send json.

REST request from app works, but not from javascript

I'm building an app that has to get and set data at a remote web service through requests. When I use the jQuery GET request it works fine, I can request data from the service without any problems, but when I use PUT I get some erros:
OPTIONS http://myurl.com 501 (Unsupported method
('OPTIONS'))
OPTIONS http://myurl.com Origin null is not allowed by Access-Control-Allow-Origin.
I've tried almost anything to get this to work, but it won't work. I've download a chrome app called REST Console, which can make custom REST requests. The strange thing is that I can interact with my server over that app but not through my javascript!
This is the javascript:
$.ajax({
url: 'http://myurl.com',
type: 'PUT',
data: '<time>16:00</time>',
success: function(data) { alert(data); }
});
Could anybody tell me what is going on here?
First ensure you're serving the page that runs the script from a web server, not directly from the file system.
I'm guessing your service at http://myurl.com is at a different host name to the host name your page is being served from? For it to work in this case you need to implement HTTP headers to support Cross Origin Resource Sharing.
Your service at http://myurl.com needs to handle an HTTP OPTIONS request, the response to which should be a set of HTTP headers (with no content) as follows:
Access-Control-Allow-Origin: http://url-of-page-with-javascript/
Optionally you can also specify Access-Control-Allow-Credentials, Access-Control-Allow-Headers and Access-Control-Allow-Methods. See the full specification here.
You'll also need to add the same headers with the same values when your server responds to the PUT request - obviously the content will also be included with this response.

GET working fine where POST in not working XMLHttpRequest

My GET request is working fine and responding as xml.
https://mydomain.com/mypage.php?id=123&nm=ak_dhara
Note: our php page is on https.
But POST is not working.
xhttp.open("POST"," https://mydomain.com/mypage.php",true);
xhttp.setRequestHeader("Content-type","application/xhtml+xml");
xhttp.send("id=123&nm=ak_dhara");
Any Suggestion ?
xhttp.setRequestHeader("Content-type","application/xhtml+xml") is wrong. If you want to ask for XHTML content, then the right request header name is Accept. If you want to identify the type of content that you're sending, then you're sending application/x-www-form-urlencoded. A server that respects the headers will try to read the data that you sent, id=123&nm=ak_dhara, as a special kind of request encoded using the application/xhtml+xml format; and no PHP server knows how to do that. It might work in certain browsers because they know that's not a valid content type, and they ignore that header and send the correct value anyway.
By the way, application/x-www-form-urlencoded is the default one, so you don't have to set it explicitly.

Http-Method changes from POST to OPTIONS when changing Content-Type

I am using closure library to do a simple POST. I think XhrIo should work because from my machine when I use any other rest client ,like Firefox browser app RESTClient or Chrome's Simple Rest Client , I can make POST request to the server and content type is application/json.
But from my application I am unable to make a post.
I am using the following code
xhr = new goog.net.XhrIo;
xhr.send('http://myhost:8181/customer/add','POST', goog.json.serialize(data));
If I leave the headers default, I get this
Encoding: UTF-8
Http-Method: POST
Content-Type: application/x-www-form-urlencoded;charset=UTF-8
If I try to change the header by passing {'content-type':'application/json'} as 4th parameter, header changes to
Http-Method: OPTIONS
Content-Type:
Shouldn't I be able to change headers appropriately with Closure library just as RESTClient does with XMLHttpRequest using JQuery ?
How else can the header be altered to make it appear like this
Encoding: UTF-8
Http-Method: POST
Content-Type: application/json;charset=UTF-8
Appreciate any help
Eddie
When you add a header to an XHR object, most browsers will do a preflight request, which is the OPTIONS method that you are seeing. There is not a way to circumvent this if you are adding custom headers, unfortunately. The POST will be sent after the OPTIONS.
This article explains the OPTIONS request a bit. I ran into issues with the preflight a while back, if that is any help.
If you have specific issues with the OPTIONS request you should edit your question to include them; otherwise, this is expected behavior.
FWIW mine also failed to update the type when I specified...
{'content-type':'application/json'}
However, if I corrected the case to
{'Content-Type':'application/json'}
... it worked.
Go figure.
If you are pass Content-Type on authorization request it will convert POST method to OPTIONS method so while we are use ouath and passing authorization token that time do not required Content-Type.
So do not pass Content-Type on all authorization request it won't change your method POST to OPTIONS

How to do cross domain ajax in jQuery with dataType 'text'?

In my javacript function I call this ajax. It works fine but only when I access the web page from firebird server. I have the same code on my testing server. The ajax asks to download some files but only firebird server has its ip registers with our clients to be able to scp there. I need to do the same if I access the php files from testing server. All the servers are inside intranet.
is it possbile to use dataType text to do so?
do I need to do any changes on the server side?
ajax call:
url = "https://firebird"+path+"/tools.php?";
jQuery.ajax({
type: 'get',
dataType: 'text',
url: url,
data: {database: database_name, what: 'download', files: files, t: Math.random() },
success: function(data, textStatus){
document.getElementById("downloading").innerHTML+=data;
}
});
Update 1
My little web application restores databases so I can do my testing on them. Now I want to enhance it so I can connect to our customers and download a particular backup. Our customer allowed only firebird server to connect to their networks. But I have my own server dedicated to testing. So every time I want to download a database I need to connect firebird. The source of my web application and the folder with all backups are mounted into the same location on both servers firebird and testing. Right now my solution (for downloading) works but only from firebird. I work basically only testing server though.
Update 2
I make two ajax calls. One is pure jQuery call (I guess I can apply any solution to this one) and the other one is ajax call from jsTree. I created new question for that one. I seems to me that I have to go for #zzzz's option b).
To do cross domain requests, your options are fairly limited. As #Mrchief mentioned, you could do server side proxy and jsonp.
Another option is Cross-Origin Resource Sharing (CORS), a W3C working draft. Quoting from this blog post:
The basic idea behind CORS is to use custom HTTP headers to allow both
the browser and the server to know enough about each other to
determine if the request or response should succeed or fail.
For a simple request, one that uses either GET or POST with no custom
headers and whose body is text/plain, the request is sent with an
extra header called Origin. The Origin header contains the origin
(protocol, domain name, and port) of the requesting page so that the
server can easily determine whether or not it should serve a response.
You can find some live examples on this site.
You will need to make changes to the server side, to accept the CORS requests. Since you have control over the server, this shouldn't be a problem. Another downside with CORS is that, it might not be compatible with older browsers. So, if some of your essential audiences use incompatible browsers, the server side proxy may actually be a better option for you.
I just want to offer an alternative.
I am not too sure regarding your network setup, but if you have access to the DNS, maybe it would be easiest if you just give your servers some arbitrary subdomain of the same domain. Something like www.foo.com for the webfront and firebird.private.foo.com for the firebird server. This way, it becomes cross subdomain instead of cross domain. Then somewhere in your JavaScript on both pages,
document.domain = "foo.com";
This gentleman achieved this solution here.
You have the following options with you
a) You use jsonp type as your datatype but this involves making changes on the server side to pass the data back as json and not as txt.. this change might be as simple as
{
"text":<your current text json encoded>
}
and on your js side you use this as response.text; Having said that if you are getting the textis for you file from sm other domain I am not sure how easy it is for you to change the code.
b) The other option is you write a handler/end point on your server i.e within your domain that will make an HTTP request to this third domain gets the file and you send the file back to your client and effectively now your client talks to your domain only and you have control over everything. as most of yoyr questions are based on ruby here is an example:
req = Net::HTTP.get_response(URI.parse('http://www.domain.com/coupons.txt'))
#play = req.body
you can find more details about the same here.
Hope this helps.
Another idea is to use you web server as a proxy. You will need to consider the security implications for this route.

Categories

Resources