Http connection in Angular 5 - json

I am currently building my first Angular 5 application that has to interact with my Java Rest Web Services that I built using [Spring Boot]
(https://www.javatpoint.com/spring-boot-tutorial).
I wrote my first HTTP connection by following various tutorials. My goal is to perform a POST; I did the following:
I created a file called proxy-config.json [web services are obtainable in localhost:8080]:
{
"/*": {
"target": "http://localhost:8080",
"changeOrigin": true,
"secure": false,
"logLevel": "info"
}
}
And edited the start line in package.json to:
"start": "ng serve --proxy-config proxy-config.json",
I then wrote a http-post in a save-data.component.ts file [logMe() is a button click event]:
logMe() {
let body = JSON.stringify({ "userEmail": this.userEmail, "userPassword": this.userPassword} );
this.http.post('/logging', body, httpOptions).subscribe(
data => {
console.log( data );
},
error => {
console.error("There Is Something Wrong\nPlease Try Again Later...");
}
);
console.log ( body );
}
The problem is that, when I send the post I receive the following
error on the browser's console:
POST http://localhost:4200/logging 404 (Not Found)

Can you try with this one?
{
"/api": {
"target": "http://localhost:8080",
"secure": false,
"pathRewrite": {"^/api" : ""}
}
}
Also, make sure proxy-config.json is in root folder

Related

How to prevent Vercel routing to not finding the page

I am building a project using NextJs and Vercel, but, when the users try to access a new page or route, the Vercel gives them the 404 error.
In other projects, I used Netlify as router and this error was fixed using the netlify.toml config file, but, I am not able to do the same using the vercel.json file.
Can you guys help me to turn this file:
netlify.toml
[[redirects]]
from = "/*"
to = "/index.html"
status = 200
Into a vercel.json config file?
I was trying with this settings:
vercel.json
{
"rewrites": [{ "source": "/(.*)", "destination": "/index.html"}]
}
But it did not solved my issue.
A workaround is to use a catch all route that immediately redirects to the index page. For example:
// [...404].jsx
export default function Page() {
return null;
}
export function getServerSideProps() {
return {
redirect: {
destination: '/',
permanent: false,
},
};
}

Cypress intercept API JSON response and extract URL

My web app sends an API POST request to create an application and returns JSON response. I want to access one particular JSON object from that response.
My JSON starts like this
[
{
"status_code": 201,
"body": {
"created": "2021-01-28T00:00:00Z",
"modified": "2021-01-28T00:00:00Z",
"id": "a2d86d17-9b3c-4c4d-ac49-5b9d8f6d6f8f",
"applicant": {
"id": "07f1e1d3-0521-401b-813e-3f777f2673c6",
"status": "Pending",
"first_name": "",
"last_name": "",
"URL": "some onboarding url"
And I wanna take that URL in the JSON response and visit it later in my cypress automation script.
Notice that the JSON repsonse starts with a square bracket not a curly bracket, which means, the whole response is an object, I assume?
My cypress script looks like this
cy.contains('button', 'CONTINUE').click()
cy.EmailGen('candidate').then(email => {
cy.get('#emails\\[0\\]').type(`${email}`)
cy.wrap(email).as('candidateEmail')
})
//writing intercept here, before the Send application button, which triggers the POST req.
cy.intercept('/hr/v1/applications/invite').as('getURL')
cy.get('button').contains('SEND APPLICATION').click({ force: true })
//waiting on the alias of intercept and using interception to print objects from response
cy.wait('#getURL').then((interception)=> {
cy.log(interception.response.body.applicant.URL)
})
cy.Logout()
The script executes with no errors. Just that nothing is logged in the cy.log statement. Below is the screen.
I also tried using another method as given below.
cy.intercept('/hr/v1/applications/invite',(req) => {
req.reply((res=> {
expect(res.status_code).to.equal('201')
expect(res.body.applicant.status).to.equal('Pending')
}))
})
In this case, I get a assert error embedded with the request and response along with some other stuff which I am unable to understand.
The complete error goes something like this...
"expected The following error originated from your test code, not from Cypress.\n\n > A response callback passed to req.reply() threw an error while intercepting a response:\n\nexpected undefined to equal '201'\n\nRoute: {\n "matchUrlAgainstPath": true,\n "url": "/hr/v1/applications/invite"\n}\n\nIntercepted request:{} Intercepted response: {} When Cypress detects uncaught errors originating from your test code it will automatically fail the current test. to include window.zE is not a function"
Its a bit weird to read this..
My application sometimes throws this exception, which I have handled using following code.
cy.on('uncaught:exception', (err, runnable) => {
expect(err.message).to.include('window.zE is not a function')
done()
return false
})
I really hope I have explained everything here. Please, help a noob.
Regards
As Richard Matsen suggested in the comments,
I used console.log(interception.response) and checked the console output in the browser controlled by Cypress.
I Noticed that the response json structure was something different than what I got in the network tab of developers tools, while using the web app.
The response was something like below...
{headers: {…}, url: "https://example.com/hr/v1/applications/invite/batch/", method: null, httpVersion: "1.1", statusCode: 200, …}
body: Array(1)
0:
body:
applicant: {id: "c6b2d686-d4f3-483e-abc8-e4641c365845", status: "Pending", first_name: "", last_name: "", email: "qa2+candidate879#example.com", …}
applicant_status: "NONE"
applicant_status_label: "None"
created: "2021-01-29T00:00:00Z"
get_applicant_status_display: "None"
id: "ad2939f5-c8ab-490a-a9e1-b0474de69e2c"
URL: "some url"
This made me modify the json traverse to
interception.response.body[0].body.applicant.URL
If others have a neat way to handle this, please let me know!

html-to-xlsx jsreport recipe with initial xlsx template file - HTTP API request

I try to generate xlsx-to-html recipe report with JsReport HTTP API https://jsreport.net/learn/api and initial attached xlsx template.
The documentatio is missing how to build request body to pass additional xlsx file like in bleow examples:
html-to-xlsx recipe example: https://playground.jsreport.net/w/admin/QiHIBqsq
xlsx recipe example: https://playground.jsreport.net/w/anon/Hy_V2BSh-4
I tried to add in template object following object:
template: {
...
engine: "handlebars",
recipe: "html-to-xlsx",
xlsxTemplate: {
content: "base64_string_of_template_xlsx_file_........."
}
...
}
but with no success.
How should be constructed JSON body for this request?
I managed to find proper json that is consumed properly by JsReport:
{
"Template": {
"Content": "template def string..",
"Recipe": "html-to-xlsx"
"Engine": "handlebars",
"BaseXlsxTemplate": {
"Content": "base-template-string-encoded-as-base64",
},
"HtmlToXlsx": {
"InsertToXlsxTemplate": true,
"WaitForJS" = false,
"HtmlEngine" = "chrome"
}
},
"Data": "Json data...",
"Options": {...}
}

Configuring Nightwatch to run tests on a standalone instance of Chrome

I am trying to setup Nightwatch so that I do not have to use Selenium and instead point directly to an instance of Chrome on Linux, but I seem to be unable to connect to the chromedriver instance.
nightwatch.json
{
"src_folders" : ["tests"],
"output_folder" : "reports",
"custom_commands_path" : "",
"custom_assertions_path" : "",
"page_objects_path" : "",
"globals_path" : "globals.js",
"selenium" : {
"start_process" : false,
"cli_args" : {
"webdriver.chrome.driver" : "./chromedriver"
}
},
"test_settings" : {
"default" : {
"selenium_port" : 9515,
"selenium_host" : "127.0.0.1",
"silent": true,
"screenshots" : {
"enabled" : false,
"path" : ""
},
"desiredCapabilities": {
"browserName": "chrome",
"acceptSslCerts": true
}
}
}
}
After attempting to run a simple test suite, I get the following error
~/scripts/TestNightwatch$ nightwatch
[Test] Test Suite
=====================
Running: Demo test Google Error processing the server response:
unknown command: wd/hub/session
Error retrieving a new session from the selenium server
Connection refused! Is selenium server started? { value: -1, error:
'Unexpected token u in JSON at position 0' }
Have I not configured nightwatch properly to connect to Chrome? Am I missing any pieces of the puzzle?
Thanks in advance!
globals.js
var chromedriver = require('chromedriver');
module.exports = {
before : function(done) {
chromedriver.start();
done();
},
after : function(done) {
chromedriver.stop();
done();
}
}
The issue may be that Chromedriver is expecting commands at / instead of /wd/hub. To fix, start Chromedriver with --url-base=/wd/hub
Source: Selenium WebDriverJS, cannot build webdriver for Chrome and https://github.com/webdriverio/webdriverio/issues/113
You need to start chromedriver in your external globals file. It looks like your config is correct. Just setup your before and after functions in the external globals module to start chromedriver.
before : function(done) {
chromedriver.start();
done();
},
after : function(done) {
chromedriver.stop();
done();
}
Take a look at the Getting Started guide for more details.

Groovy property not recognized in ElasticSearch Watcher Transform Script getting proper JSON

I'm using:
Elasticsearch 2.3
Watcher
Topbeat
The goal is to create a watch that every x amount of time does a query and retrieves some hits, and post it to a web server. This works fine. However, the Json response in {{ctx.payload.hits.hits}} isn't Json, so I can't proccess it. The same issue seems to appear in some threads, this being the most similar to mine:
So, this is my watch (the input works fine, the issue is in the script of the action):
PUT _watcher/watch/running_process_watch
{
"trigger" : {
"schedule" : {
"interval" : "10s"
}
},
"input" : {... },
"actions" : {
"ping_webhook": {
"transform":{
"script": "return [ body: groovy.json.JsonOutput.toJson(ctx.payload.hits.hits)]"
},
"webhook": {
"method": "POST",
"host": "localhost",
"port": 4567,
"path": "/register_data",
"headers": {
"Content-Type" : "application/json"
},
"body" : "data: {{ctx.payload.body}}"
}
}
}
}
The error:
failed to execute [script] transform for [running_process_watch_0-2016-06-08T17:25:14.162Z]
ScriptException[failed to run inline script [return [ body: groovy.json.JsonOutput.toJson(ctx.payload.hits.hits)]] using lang [groovy]]; nested: MissingPropertyException[No such property: groovy for class: 1605d064acb49c10c464b655dacc9193f4e2e484];
at org.elasticsearch.script.groovy.GroovyScriptEngineService$GroovyScript.run(GroovyScriptEngineService.java:320)
at org.elasticsearch.watcher.transform.script.ExecutableScriptTransform.doExecute(ExecutableScriptTransform.java:74)
at org.elasticsearch.watcher.transform.script.ExecutableScriptTransform.execute(ExecutableScriptTransform.java:60)
at org.elasticsearch.watcher.transform.script.ExecutableScriptTransform.execute(ExecutableScriptTransform.java:41)
at org.elasticsearch.watcher.actions.ActionWrapper.execute(ActionWrapper.java:94)
at org.elasticsearch.watcher.execution.ExecutionService.executeInner(ExecutionService.java:388)
at org.elasticsearch.watcher.execution.ExecutionService.execute(ExecutionService.java:273)
at org.elasticsearch.watcher.execution.ExecutionService$WatchExecutionTask.run(ExecutionService.java:438)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Any idea to make groovy.json usable inside the watcher action script? Or any other idea to return proper json from the ctx.hits.hits?
So, I opened an issue in Elasticsearch repo. After some discussion, a native toJson function is going to be implemented in the mustache templating engine so it renders json by default.
Here is the pull request.
Hopefully in the next release will be ready.