Javascript not showing notification from GET springboot rest api - javascript

I am totally new to javascript . I just want to show a notification using notify.js when a button is clicked.
Following is my RestController code:
#RequestMapping(value = "/checkCurrentBranch" , method=RequestMethod.GET)
public String checkCurrectGitBranch(Model model, HttpServletResponse response) {
String branchName = "";
GitInfo gitInfo = new GitInfo();
JsonFactory factory = new JsonFactory();
String json = apiService.readGitProperties();
ObjectMapper mapper = new ObjectMapper(factory);
JsonNode rootNode;
try {
rootNode = mapper.readTree(json);
Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();
while (fieldsIterator.hasNext()) {
Map.Entry<String, JsonNode> field = fieldsIterator.next();
if (field.getKey().toString().equalsIgnoreCase("git.branch")) {
branchName = field.getValue().toString();
adminAppLogger.info("Current Branch name :: "+branchName);
}
}
} catch (IOException e) {
adminAppLogger.error("Error while getting current Git branch :" + e);
branchName = "Error while fetching branch name";
}
model.addAttribute("res", branchName);
return branchName;
}
Following is my js code:
$('#gitBranch').click(function(res) {
/* <![CDATA[ */
var path = /* [[#{/}]] */'checkCurrentBranch';
/* ]]> */
$.notify(res, "info");
console.log(res);
});
I think I am missing some points but I am stuck. Any suggestions?
I tried using axios following is my js:
$('#gitBranch').click(function(res) {
/* <![CDATA[ */
var path = /* [[#{/}]] */'checkCurrentBranch';
/* ]]> */
axios({
method:'get',
url:path,
responseType:'json'
})
.then(function (response) {
console.log(response)
$.notify(data,"info")
});
});
Following response I get on brwoser console. Now I just want that data field to be shown as notification :
{data: "qc_mediaworker_details", status: 200, statusText: "", headers: {…}, config: {…}, …}
config
:
{adapter: ƒ, transformRequest: {…}, transformResponse: {…}, timeout: 0, xsrfCookieName: "XSRF-TOKEN", …}
data
:
"qc_mediaworker_details"
headers
:
{pragma: "no-cache", date: "Sun, 04 Nov 2018 05:59:32 GMT", x-content-type-options: "nosniff", x-frame-options: "DENY", content-type: "application/json;charset=UTF-8", …}
request
:
XMLHttpRequest {onreadystatechange: ƒ, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}
status
:
200
statusText
:
""
__proto__
:
Object

You need to properly use data key in axios response block.
axios({
method:'get',
url:path,
responseType:'json'
})
.then(function (response) {
console.log(response)
$.notify(response.data,"info")
});
In above code, I replaced data by response.data
, because according your give code, data is not declared, that means its undefined. So if you mean data to that data which you get in axios response, then you need to access data by $.notify(response.data,"info") instead of $.notify(data,"info")

You don't have anywhere http request.
I recommend you using axios (because it's simple)
Sample code:
axios.get('host:port/checkCurrentBranch')
.then(response => {
// do what you want to do
})
.catch(error => {
// do something if an error occurs
})

Related

How handle errors with JS fetch again Laravel Api

My Goal
I would like to display the error messages in the Form. But for this I would need to have access to the JSON?
Code
HTML blade
<form>
<input name="name">
<p class="text-red-500 text-xs italic">Please fill out this field.</p> {{-- $message --}}
<button id="submit">SUBMIT</button>
</form>
javascript
<script>
const submitBtn = document.getElementById('submit');
submitBtn.addEventListener('click', (e) => {
e.preventDefault();
const fel = document.getElementById('commentForm');
const formData = new FormData(fel);
const url = '/api/comments';
let fetchData = {
method: 'POST',
body: formData,
headers: new Headers()
}
fetch(url, fetchData)
.then(response => {
if (!response.ok) {
return Promise.reject(response);
}
return response.json();
})
.then(data => {
console.log("Success");
console.log(data);
})
.catch(error => {
if (typeof error.json === "function") {
error.json().then(jsonError => {
console.log("Json error from API");
console.log(jsonError);
}).catch(genericError => {
console.log("Generic error from API");
console.log(error.statusText);
});
} else {
console.log("Fetch error");
console.log(error);
}
});
</script>
Response after a faulty request
HttpStatus: 400
// console.log(res) output
Response { type: "basic", url: "http://127.0.0.1:8000/api/comments", redirected: false, status: 400, ok: false, statusText: "Bad Request", headers: Headers, body: ReadableStream, bodyUsed: false }
​
body: ReadableStream { locked: false }​
bodyUsed: false​
headers: Headers { }​
ok: false​
redirected: false​
status: 400​
statusText: "Bad Request"​
type: "basic"​
url: "http://127.0.0.1:8000/api/comments"
​
<prototype>: ResponsePrototype { clone: clone(), arrayBuffer: arrayBuffer(), blob: blob(), … }
repellendus-dolor-quibusdam-sint-qui-news:147:29
Problem
In the Devtool Network tab, when I go to response of the request, I get a JSON
JSON: {"comment_content":["The comment content field is required."],"comment_name":["The comment name field is required."]}
When I output res.json() via the console within my fetch method, I get a Promise:
XHRPOSThttp://127.0.0.1:8000/api/comments
[HTTP/1.1 400 Bad Request 100ms]
Promise { <state>: "pending" }​
<state>: "fulfilled"​
<value>: Object { comment_content: (1) […], comment_name: (1) […] }​​
comment_content: Array [ "The comment content field is required." ]​​
comment_name: Array [ "The comment name field is required." ]​​
<prototype>: Object { … }
Additional question:
Is there a better way to display the errors from the response in the form? Maybe with the help of the form data object?
Considering you are making the request from JavaScript means you will also need to update the UI to reflect any error states. This includes targeting the right input elements based on the validation errors and appending them to the DOM. There may be libraries which can make this easier on the JS side but ultimately, you will need to write this logic.
As an aside, if you were using a traditional POST request, Laravel provides the $errors variable and #error blade directive. These help check for / display validation errors and are available in your application views. Since you are using blade, you may want to consider this.

Mendeley API File Download Fails

I am trying to use the Mendeley API to download a file attached to a resource (document). I am following the developer documentation here:
https://dev.mendeley.com/methods/#downloading-a-file
It looks like it should be fairly straight forward. I have the Oauth flow figured out and I am able to pull all of my documents from Mendeley library. I am also able to get the attached file id for a given document.
It is when I try to use that ID to retrieve the file (a pdf in this case) that it fails. I have copied the parameters to postman and it works fine there. But when I try to do it in my Ruby-on-rails app using javascript it fails.
I am a novice when it comes to javascript so I may very well be missing something obvious.
Here is the javascript code snippet:
downloadFile = (json) => {
this.getAuthCode();
this.provideToken = (token) => {
const access_token = token;
var myHeaders = new Headers();
myHeaders.append("Authorization", `Bearer ${access_token}`);
var requestOptions = {
method: 'GET',
headers: myHeaders,
};
fetch(`https://api.mendeley.com/files/${json[0].id}`, requestOptions).then(resp => {
console.log(resp)
})
}
}
The json argument is an array of files associated with a document. It seems to work ok until the Mendeley server redirects to the AWS S3 storage URL for the file in question. Here is the Chrome developer console output:
`Response {type: "cors", url: "https://mendeley-files.s3.amazonaws.com/31/9f/319f…09d6b8443d1e734fad70c551e37a0a3497b42c69fd0796c91", redirected: true, status: 400, ok: false, …}
body: (...)
bodyUsed: false
headers: Headers
__proto__: Headers
ok: false
redirected: true
status: 400
statusText: "Bad Request"
type: "cors"
url: "https://mendeley-files.s3.amazonaws.com/31/9f/319fe16b678cc65092ef5aa732b3e4c137f272f3?response-content-disposition=attachment%3Bfilename%3D%222003-Psychometric_properties_of_student_ratings_of_instruction_in_online_and_on-campus_courses.pdf%22&response-content-type=application%2Fpdf&X-Amz-Security-Token=IQoJb3JpZ2luX2VjEOz%2F%2F%2F%2F%2F%2F%2F%2F%2F%2FwEaCWV1LXdlc3QtMSJIMEYCIQCP0qEL1EJeGKIBVmxX2FaPIZftcmqiW%2FzgDY5ysRs25AIhAMM6q3YzWSubSnuuXOs9gi8voOZ%2BRrkQS343IkihJka1KvYDCDUQAhoMMTA4MTY2MTk0NTA1Igx2zsOuUuv1h6V8cw0q0wMNdVy5izfbA30MysjiNXG3V%2F21aHfn2xXF8ZKq74%2FAbDUbTzKfFWuN79ARNbEyeGinrXdlRXb%2FlEP9ZRgb6xh1%2BtCBtpqT8esZmdZcERC%2Fpup8dtd8q%2BWeCxVKVIyYZffZJvJW1wQOONhMJnfpb751Lr1pTN%2BAu38q8Dky8sOB%2B%2FyH0xOXbP5S0IFErM0B1Ac7eJLOTLrrzwuQ17Z1ZF%2FN5ZenKtV5rrIRR8RU0%2FnzY6EQip1LIHy7l%2F0rN9srGyM1n3fT5trqKL7H6mi79ZlbN0RJ%2FZAtO6pWTL6DbpFzrlCTt6fI%2B2UqdEDrVBO4QT8ROYnd8dYd%2F3hrB1%2BOjuugRDRE6tUehgn9lnFWUndww0XHOWUq8GWAOImeBts7fazUmcCv8lzhH09FYwbcaOKghr6HhJko5UUpeGV4TjMVCA1wUZ4G3DBBVTUIKBLbve0oWFexVFj2J380neGXywdPbEzUcp5o6N%2FEGOW5nMJHlwIquMDubiwgrQ5ANES6RhuO%2BBQTHuy9JdL2KrfhEHA3UJBm6T4Azg1XgEIpXo84Hs7cc2x7ewZ6CPUyzXcc%2Bx72u1o6RwoE12AKdp%2BwqZK4NnFmn6jXKKCSShgmVuqUr3ARVTDmy%2Bb1BTruAQmSrzEXqXzi5Ut4AWjWCEMvw4mB5Yk8W6v5V6YTRtwp8ebqI9Q4hzfMT62ko1AQsBwhKX8anZTIvDVpImcjbUQnaWVGKehj0OGVOb%2FnCn3JXZRq2bCKfQ2Mf7YxlWSHIy9CWqZiW4uTpdSfk5kOOnYQhrKhHQJc%2BM%2F7BldOy72AVgikcmvQdR3k315KNwh%2BJ96ci4LvRa%2BiXw5stATLCQCSKWPYCRonCighfGxNoAyWvvuTkjaQe3bm6X64Giwm2qyyAso05hnC3gotbefpEFNjx2%2Brgm2G%2FzNwdKkr2I%2BFy%2BnGXVNNG2ruh2DMVOw%3D&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20200511T205618Z&X-Amz-SignedHeaders=host&X-Amz-Expires=600&X-Amz-Credential=ASIARSLZVEVE5V2CTSJF%2F20200511%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Signature=96b2a6673ab742909d6b8443d1e734fad70c551e37a0a3497b42c69fd0796c91"
__proto__: Response
arrayBuffer: ƒ arrayBuffer()
blob: ƒ blob()
body: (...)
bodyUsed: (...)
clone: ƒ clone()
formData: ƒ formData()
headers: (...)
json: ƒ json()
ok: (...)
redirected: (...)
status: (...)
statusText: (...)
text: ƒ text()
type: (...)
url: (...)
constructor: ƒ Response()
Symbol(Symbol.toStringTag): "Response"
get body: ƒ body()
get bodyUsed: ƒ bodyUsed()
get headers: ƒ headers()
get ok: ƒ ok()
get redirected: ƒ redirected()
get status: ƒ status()
get statusText: ƒ statusText()
get type: ƒ type()
get url: ƒ url()
__proto__: Object`
It clearly finds the correct file but fails to download it. When I run it in postman it downloads the file.
I have tried adding various headers that show up in Postman as 'hidden' but I get basically the same response. Any thoughts or direction on this would be greatly appreciated.
Stay safe!
Reference documentation: https://dev.mendeley.com/code/core_quick_start_guides.html#file_download
This is working for me:
async function getFile(fileId) {
const url = `https://api.mendeley.com/files/${fileId}`;
const res = await superagent.get(url).auth(accessToken, { type: 'bearer' });
const [fileUrl] = res.redirects;
return fileUrl;
}

Cache Storage API, can't get header back

I would like to a check for max-age so I remove items from cache when they get old, but I can't get my own header back for some reason.
export function cacheResponse(url, response) {
caches.open('my-cache').then(function(cache) {
cache.put(url, new Response(JSON.stringify(response), {
headers: {
'Cache-Control': 'max-age=1',
'Content-Type': 'application/json;charset=UTF-8'
}
}));
});
}
cacheResponse('/hello', {hello: "world"})
I can see this working in the Application tab in chrome and I can see those 2 headers in the preview, but when I pull the item back out the headers object is null.
cache.match(url).then(async function(object) {
console.log(object.headers) // null
var body = await object.clone().json(); // {hello: "world"}
})
The object looks like this
object: Response
body: ReadableStream
bodyUsed: false
headers: Headers
__proto__: Headers
ok: true
redirected: false
status: 200
statusText: ""
type: "default"
url: ""
Seems like I should be able to lookup the headers from calling match() no?
That should work; you should be able to call response.headers.get('cache-control') to retrieve the value (assuming this is a same-origin response).
Here's a snippet of code that I just tested which worked when run in the JS console:
async function test() {
const constructedResponse = new Response('test', {
headers: {'cache-control': 'max-age=1'}
});
const cache = await caches.open('test');
cache.put('/test', constructedResponse);
const matchedResponse = await cache.match('/test');
console.log(`cache-control: ${matchedResponse.headers.get('cache-control')}`);
}

How do you properly send a proper HTTP Response in CakePHP 3.5

I am developing an CakePHP app that the Models for my ReactJS application, but I have run into a problem using Axios to retrieve a dynamically created json from one of the endpoints in the CakePHP application.
The action in the controller looks like this:
public function bootstrap($name = null){
$this->autoRender = false;
$config = $this->Themes->getJson($name);
$config += $this->systemVars();
$output = json_encode($config);
$this->response
->withHeader('Access-Control-Allow-Origin','*')
->withHeader('Access-Control-Allow-Methods',['GET', 'POST'])
->withHeader('Access-Control-Max-Age','8600')
->withType('application/json')
->withStringBody($output);
return $this->response;
}
and the axios request in my React app looks like this:
axios.get('https://demo.axistaylor.com/ccsllc/themes/json')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
Everything seems to work fine except this the response that is printed to the console when I run the react app.
{
config: {adapter: ƒ, transformRequest: {…}, transformResponse: {…},
timeout: 0, xsrfCookieName: "XSRF-TOKEN", …},
data:"",
headers:{pragma: "no-cache", content-type: "text/html; charset=UTF-8",
cache-control: "no-store, no-cache, must-revalidate", expires: "Thu, 19 Nov 1981 08:52:00 GMT"},
request: XMLHttpRequest {onreadystatechange: ƒ, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …},
status: 200,
statusText: "OK",
…
}
The data comeback as an empty string "". I have tried changing the method of setting the body and headers, even reverting to the methods supported by prior versions of CakePHP, eg. $this->response->header(…)->body(…), and the results are the same. The endpoint listed in the axios request is public so you can test it yourself. https://demo.axistaylor.com/ccsllc/themes/json
The problem was the initial $this->response is immutable in CakePHP 3.5+, and has to be reassigned with header and body in one statement like this.
$this->response = $this->response
->withHeader('Access-Control-Allow-Origin','*')
->withHeader('Access-Control-Allow-Methods',['GET', 'POST'])
->withHeader('Access-Control-Max-Age','8600')
->withType('application/json')
->withStringBody($output);
for information look as the answer to the question here provided by ndm

Display json data in angular

I have a post that runs on page load. I am trying to get data objects in json to use on my page and in my controller so I am trying to store the value in Angular scope.
I do not know where I have gone wrong but I cant get the value and when I console.log I get
angular.js:11655 ReferenceError: data is not defined
I want to store
c_name
max_slots
base_image
Summery of what I need
I need my array objects listed above stored in scope variables so that I may use them in my html and else where in my JavaScript controller.
My json
{data: Array(1), status: 200, config: {…}, statusText: "OK", headers: ƒ}
config
:
{method: "POST", transformRequest: Array(1), transformResponse: Array(1), url: "http://www.site.co.uk/one/two/getdata", date: {…}, …}
data
:
Array(1)
0
:
c_name
:
"ben"
d_text
:
[]
max_slots
:
2
resolution
:
(2) [1920, 1080]
slots
:
Array(3)
0
:
{path_image: "", base_image: "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD…O7/aaFdrXd6na2UApSIJEwod/rWVlSUUk2h2Gbknfi6P/2Q==", slot_id: 1}
1
:
{path_image: "", base_image: "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD…O7/aaFdrXd6na2UApSIJEwod/rWVlSUUk2h2Gbknfi6P/2Q==", slot_id: 2}
2
:
{path_image: "", base_image: "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD…O7/aaFdrXd6na2UApSIJEwod/rWVlSUUk2h2Gbknfi6P/2Q==", slot_id: 3}
length
:
3
__proto__
:
Array(0)
__v
:
0
_id
:
"59c92d6f45b79c8c110ee6ab"
__proto__
:
Object
My script I am trying to get the data
My JavaScript
$scope.GetData = function () {
$http({
url: "http://www.site.co.uk/one/two/getdata",
method: "POST",
date: {},
headers: {'Content-Type': 'application/json'}
}).then(function (response) {
// success
console.log('you have received the data ');
console.log(response);
// $scope.base_image = response.base_image; $scope.c_name = response.c_name;
$scope.c_name = data.c_name;
$scope.max_slots = data.max_slots;
$scope.slot_image = data.slots.base_image;
console.log($scope.c_name);
}, function (response) {
// failed
console.log('failed getting campaigns goo back to log in page.');
console.log(response);
});
};
$scope.GetData();
Full response from console.log(data);
you have received the data
{data: Array(1), status: 200, config: {…}, statusText: "OK", headers: ƒ}
config
:
{method: "POST", transformRequest: Array(1), transformResponse: Array(1), url: "http://www.site.co.uk/one/two/getdata", date: {…}, …}
data
:
Array(1)
0
:
c_name
:
"ben"
d_text
:
[]
max_slots
:
2
resolution
:
(2) [1920, 1080]
slots
:
[{…}]
__v
:
0
_id
:
"59c92d6f45b79c8c110ee6ab"
__proto__
:
Object
length
:
1
__proto__
:
Array(0)
headers
:
ƒ (c)
status
:
200
statusText
:
"OK"
__proto__
:
Object
And a screen shot
I understood as you have to print JSON data for that I'm posting this answer, if you not expect this answer please post your question more clearly.
$scope.GetData = function () {
$http({
url: "http://www.site.co.uk/one/two/getdata",
method: "POST",
date: {},
headers: {'Content-Type': 'application/json'}
}).then(function (response) {
// success
console.log('you have received the data ');
console.log(response); // if the response data is in json
console.log(angular.toJson(response)); // if the response data is in json
// $scope.base_image = response.base_image; $scope.c_name = response.c_name;
$scope.c_name = response.c_name;
$scope.max_slots = response.max_slots;
$scope.slot_image = response.slots.base_image;
console.log($scope.c_name);
}, function (response) {
// failed
console.log('failed getting campaigns goo back to log in page.');
console.log(response);
});
};
$scope.GetData();
$scope.GetData = function () {
$http({
url: "http://www.site.co.uk/one/two/getdata",
method: "POST",
date: {},
headers: {'Content-Type': 'application/json'}
}).then(function (response) {
// success
var data = JSON.parse(response);
console.log('you have received the data ');
console.log(data);
// $scope.base_image = response.base_image; $scope.c_name = response.c_name;
$scope.c_name = data.c_name;
$scope.max_slots = data.max_slots;
$scope.slot_image = data.slots.base_image;
console.log($scope.c_name);
}, function (response) {
// failed
console.log('failed getting campaigns goo back to log in page.');
console.log(response);
});
};
$scope.GetData();
Replacing response with data should fix the issue.

Categories