res.json express not working - json

I'm trying to run a simple response.json() with express but it doesn't make the json itself.
The node.js file: server/app.js
"use strict";
let express = require('express');
let app = express();
app.use(express.static(__dirname + "/../client"));
app.get('/sports', function(request, response) {
response.json( ["Cycling", "Weightlifting"] );
});
app.listen(8181, () => console.log("Listening on 8181"));
The terminal runing the server:
$ node app.js
Listening on 8181
The "test" for the response.json():
$ curl -i localhost:8181/sports
HTTP/1.1 404 Not Found
X-Powered-By: Express
X-Content-Type-Options: nosniff
Content-Type: text/html; charset=utf-8
Content-Length: 19
Date: Fri, 10 Jun 2016 20:23:17 GMT
Connection: keep-alive
Cannot GET /sports
I really don't know what is going on because this is an example of a video in codeschool and is a copy of this git commit and everything looks the same :( https://github.com/codeschool/OlympicsMEAN/commit/767c89b8b0025861cefac910f98d79ef52cb3497
Thanks

Related

Setup Quart server with HTTP/2

I am trying to setup a Quart server to play with HTTP/2. I have been trying to go through the minimal documentation at:
https://gitlab.com/pgjones/quart
Where I have:
$ cat app.py
from quart import Quart, render_template, websocket
app = Quart(__name__)
#app.route("/")
async def hello():
return await render_template("index.html")
#app.route("/api")
async def json():
return {"hello": "world"}
#app.websocket("/ws")
async def ws():
while True:
await websocket.send("hello")
await websocket.send_json({"hello": "world"})
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5001)
Some basic check:
$ curl -I --http2 http://acme.corp:5001
HTTP/1.1 101
date: Tue, 02 Mar 2021 10:05:12 GMT
server: hypercorn-h11
connection: upgrade
upgrade: h2c
HTTP/2 200
content-type: text/html; charset=utf-8
content-length: 0
date: Tue, 02 Mar 2021 10:05:12 GMT
server: hypercorn-h2
Looking at the output
$ python3 app.py
* Serving Quart app 'app'
* Environment: production
* Please use an ASGI server (e.g. Hypercorn) directly in production
* Debug mode: False
* Running on http://0.0.0.0:5001 (CTRL + C to quit)
[2021-03-02 11:01:49,083] Running on http://0.0.0.0:5001 (CTRL + C to quit)
[2021-03-02 11:01:53,011] 10.221.0.114:53637 GET / 1.1 200 0 5817
[2021-03-02 11:01:53,255] 10.221.0.114:53637 GET /favicon.ico 1.1 404 103 1348
Here is what I see, when I load the index.html page from chrome:
What am I missing to get http/2 from chrome ?
Locally you are upgrading an insecure HTTP 1.1 request to an insecure HTTP 2 request. This works with Quart and curl, but browsers including chrome do not support insecure (unencrypted) HTTP/2. For it to work in chrome I create a self signed certificate, passing the certfile and keyfile options to the run and accept the warning chrome offers when visiting the site. An example exists here.

AEM JCR - Get response as JSON

We are adding some metadata under a specific location in JCR:
POST /some/jcr/location/_jcr_content/json HTTP/1.1
Accept: application/json
Authorization: Basic YWRtaW46YWRtaW4=
Cache-Control: no-cache
Host: localhost:4502
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Content-Type: multipart/form-data; boundary=--------------------------554953211468377919703514
Cookie: cq-authoring-mode=TOUCH
Content-Length: 383
----------------------------554953211468377919703514
Content-Disposition: form-data; name="./value"
{ "test": "test" }
----------------------------554953211468377919703514
Content-Disposition: form-data; name=":cq_csrf_token"
ey***our csrf token***-c5Oa0
----------------------------554953211468377919703514--
But when we fetch this same resource, the response type is test/html`:
GET /some/jcr/location/jcr:content/json/value HTTP/1.1
Accept: application/json
Cache-Control: no-cache
Host: localhost:4502
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Cookie: cq-authoring-mode=TOUCH
HTTP/1.1 200 OK
Date: Fri, 26 Feb 2021 13:49:38 GMT
X-Content-Type-Options: nosniff
Content-Type: text/plain;charset=utf-8
Content-Length: 18
{ "test": "test" }
What configuration do we need to add in JCR, or what do we need to edit in our request to make sure that JCR returns content type application/json.
UPDATE: As Sharath Madappa replied, you can request the data in JSON format by suffixing the location with the .json extension. However, that results in the following format:
{
"value": "{ \"test\": \"test\" }"
}
While I expect it to be:
{
"test": "test"
}
use GET /some/jcr/location/jcr:content/json/value.json while making the request. Sling is able to render/return the resource in multiple formats based on the extension in the request. By default, if no extension is provided it goes with HTML. The path tells which resource, the extension, and selectors tell how and what renders the resource.
You can also specify the depth you want to go for besides having JSON format response.
E.g
Depth of 1(just the node) in JSON format:
curl -u <user>:<pass> -v <URL>/some/jcr/location/jcr:content/json/value.1.json
All child nodes under a certain path in JSON format:
curl -u <user>:<pass> -v <URL>/some/jcr/location.-1.json
Posting JSON content and then retrieving it as Content-Type: application/json can be done by file upload instead of adding properties.
Here is a javascript example:
const data = { test: "test" };
const jsonData = new Blob([JSON.stringify(data)], { type: 'application/json' });
const formData = new FormData();
formData.append(`myFile.json`, jsonData, `myFile.json`);
return fetch(path, {
method: 'POST',
body: formData
});
This example does not take in account Authn/Authz.
To fetch you data as application/json, you just issue a GET call to the location of the JSON file:
http://localhost:4502/path/to/the/folder/jcr:content/files/myFile.json

CouchDB _session not returning cookie

Environment:
CouchDB 2.2.0 running on VirtualBox, running up-to-date Debian image. Network type is bridged, all ports are open, no https.
Vue3.js app (not using any Vue functionality to access the DB)
Remote access JS package:
axios
fetch
Browser: Chrome latest
Relevant CouchDB local.ini settings
[couch_peruser]
enable = false
delete_dbs = false
[chttpd]
port = 5984
require_valid_user = false
proxy_use_secret = false
bind_address = 0.0.0.0
authentication_handlers = {chttpd_auth, cookie_authentication_handler}, {chttpd_auth, default_authentication_handler}
[httpd]
bind_address = 127.0.0.1
enable_cors = true
(default authentication handlers set in default.ini)
authentication_handlers = {couch_httpd_auth, cookie_authentication_handler}, {couch_httpd_auth, default_authentication_handler}
[couch_httpd_auth]
secret = (hash num)
require_valid_user = false
allow_persistent_cookies = true
[cors]
origins = *
headers = accept, authorization, content-type, X-Auth-CouchDB-UserName, origin, referer
credentials = true
methods = GET, PUT, POST, HEAD, DELETE
What Happens
If I do the query via curl, I get a cookie in the response.
Here's the curl call:
curl -v http://couchman.lcldev:5984/_session \
-H "Content-Type:application/json" \
-H "X-Auth-CouchDB-UserName:<uname>" \
-d '{"name":"<uname>","password":"<passwd>"}'
And here's the response:
< HTTP/1.1 200 OK
< Cache-Control: must-revalidate
< Content-Length: 47
< Content-Type: application/json
< Date: Wed, 10 Oct 2018 21:16:10 GMT
< Server: CouchDB/2.2.0 (Erlang OTP/19)
< Set-Cookie: (cookie info)
<
{"ok":true,"name":"<name>","roles":["<roles>"]}
Yay. I get a cookie.
But if I call it from within my app (with either fetch or axios), I only get these headers:
Response headers:
cache-control,must-revalidate
content-type,application/json
server,CouchDB/2.2.0 (Erlang OTP/19)
No Set-Cookie header.
So, what's up? What am I missing?
Answered in first comment - see thread for more info.

How to read json data of a bad request (status code 400) using Alamofire

I was calling a Rest API locally from terminal. This was like below:
http -v -f --timeout=60 GET 'http://localhost:8080/api/v1/public/users/signin?email=myemail#email.com&password=mypassword'
It is returning following output:
GET /api/v1/public/users/signin?email=myemail#email.com&password=mypassword HTTP/1.1
Accept: */*
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded; charset=utf-8
Host: localhost:8080
User-Agent: HTTPie/0.8.0
HTTP/1.1 400 Bad Request
Content-Type: application/json
Date: Mon, 28 Mar 2016 16:59:08 GMT
Set-Cookie: rememberMe=deleteMe; Path=/; Max-Age=0; Expires=Sun, 27- Mar-2016 16:59:13 GMT
Transfer-Encoding: chunked
{
"debugMessage": "Submitted credentials for token [org.apache.shiro.authc.UsernamePasswordToken - najmul#qianalysis.com, rememberMe=true] did not match the expected credentials.Submitted credentials for token [org.apache.shiro.authc.UsernamePasswordToken - najmul#qianalysis.com, rememberMe=true] did not match the expected credentials.: The subject was expected to be true, but was false",
"errorCode": "INCORRECT_CREDENTIALS",
"logId": "50a695c1a81e0542",
"stackTrace": "org.niopack.r.....
}
Now I want to read this JSON data using Alamofire. I tried with responseJSON serialiser with following way:
Alamofire.request(method, urlString, parameters: parameters, encoding: .URL, headers: cookieHeader)
.validate()
.responseJSON {
alamofireResponse in
let jsonData = alamofireResponse.result.value
}
But this I am getting jsonData as nil. What you will do if you were are here?
Thanks.
For me removing the validate() allowed me to see the reason the request was failing. For some reason when validate fails, the data of the response is not parsed.

Cannot receive JSON exception message/content type on remote requests

I have a ASP.NET MVC3 application, which uses JSON to comunicate with a Flash UI.
I´m use an ActionFilterAttribute to handle JSON exceptions (from Handle JSON Exceptions Gracefully in ASP.NET MVC 2: http://www.dotnetcurry.com/ShowArticle.aspx?ID=496):
public class HandleJsonExceptionAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
if (filterContext.Exception != null)
{
filterContext.HttpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
filterContext.Result = new JsonResult()
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = new
{
filterContext.Exception.Message,
}
};
filterContext.ExceptionHandled = true;
}
}
}
It´s works ok when executes on localhost, details from fiddler:
HTTP/1.1 500 Internal Server Error
Cache-Control: private
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/7.5
X-AspNetMvc-Version: 3.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Mon, 11 Apr 2011 19:05:21 GMT
Content-Length: 34
{"Message":"No está autenticado"}
But, when executed from remote clients, on the LAN for example, I get the response in "Content-Type: text/html" instead "Content-Type: application/json;" and the content is a standard html error page:
500 - Internal server error.
There is a problem with the resource you are looking for, and it cannot be displayed.
HTTP/1.1 500 Internal Server Error
Cache-Control: private
Content-Type: text/html
Server: Microsoft-IIS/7.5
X-AspNetMvc-Version: 3.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Mon, 11 Apr 2011 19:07:53 GMT
Content-Length: 1208
What or where I need to configure something to get the JSON response on remote requests?
I need the flash UI receive a http 500 error, but with the json message instead the html.
Looking at the article the javascript only seems to be wire up for local requests.
What you need is to be using jsonp. (json with padding). This will allow you to do proper cross domain request returning a json object.
Further info can be found here and here.
I had a same problem, I solved with this code in web.config
<httpErrors existingResponse="PassTrough"></httpErrors>