nodejs restler module post test call EMPTY body? - testing

I am writing some tests for my nodejs app. Tests work ok, the only problem I'm having (using restler) is that when I test a post request the body sent in the request is always empty.
This is what I'm doing:
rest.post('http://localhost:3000/api/testpost1', {
name : "my name"
}).on('complete', function(data,res) {
console.log("status code",res.statusCode)
});
The body in the req.body on the server is always equal to: {}
What am I doing wrong?

Do this:
rest.post('http://localhost:3000/api/testpost1', {
data: {name : "my name"}
}).on('complete', function(data,res) {
console.log("status code",res.statusCode)
});

Related

No Host in request URL for Grafana datasource plugin tutorial - Add authentication

I'm trying to follow the example for developing a datasource plugin from Grafana. Ultimately I want my plugin to use Oauth, but even with just the basic Grafana datasource proxy example I seem to be having issues.
I have updated my plugin.json, class and constructor.
I have setup this hard coded example.
in plugin.json
{
"path": "grafana",
"url": "https://github.com"
}
],
And a sample testDataSource()
async testDatasource() {
return getBackendSrv()
.datasourceRequest({
url: this.url + '/grafana/grafana',
method: 'GET',
})
.then(response => {
if (response.status === 200) {
return { status: 'success', message: 'Data source is working', title: 'Success' };
} else {
return { status: 'failure', message: 'Data source is not working: ' + response.status, title: 'Failure' };
}
});
}
When I try and save/test this datasource to call that method, I get in the frontend a
HTTP Error Bad Gateway
And in the logs
t=2021-09-17T14:31:22+0000 lvl=eror msg="Data proxy error" logger=data-proxy-log userId=1 orgId=1 uname=admin path=/api/datasources/proxy/9/grafana/grafana remote_addr=172.17.0.1 referer=http://localhost:3000/datasources/edit/9/ error="http: proxy error: http: no Host in request URL"
I would've expected the request to be routed to the datasource proxy and for that to make the request to github but it seems Grafana is making a request to /api/datasources/proxy/9/grafana/grafana and nothing is picking it up?
Looking up my datasource via API, there's nothing listed for URL.
You will need to render this in your ConfigEditor.tsx
<DataSourceHttpSettings
defaultUrl="http://localhost:8080"
dataSourceConfig={options}
onChange={onOptionsChange}
/>
Which will give you the basic form with URL, whitelist, auth options that you see on most plugins. The URL there I guess should match what you have in your routes.

VueJS POST http://127.0.0.1:8000/login 404 (Not Found)

so i post this qs yesterday enter link description here
i was getting this **Uncaught (in promise) Error: Request failed with status code 405 VUEJS
**
now i did fix the part of axios from this :
axios.post('http://127.0.0.1:8000/?#/login/',{
email: this.email, password: this.password
}, headers)
.then((response)=>{
const data=response.data;
console.log(data);
})
to this
axios({
method: "post",
url: "/api/login/",
data: {
email: "",
password: ""
}
}).then(
response => {
console.log(response);
},
error => {
console.log(error);
}
);
now i'm getting this error
as u can see the problem and the api.php and the root
405 error code means your api endpoint not allow the current method you requesting to so 405 errorbis aboutbendpoint problems, and about 404 response status in axios if server's response have a 4XX status it'll go directlly on catch it should be somthing like this:
axios.post("http://127.0.0.1:8000/api/login/",{data: value,data1: value1})
.then((res)=>console.log(res))
.catch((err)=>{
// 404 will be loged below
console.log(err.response.status)
console.log(err.response)
}
i have never saw somting like this but i think you should ckeck your api server and make sure you entered the currect url and currect port and make sure in your server logic response part you have'nt a type error or somithing im really sorry if it was'nt helpful
p.s. i wrote the code above with my phone im really sorry its may be a little ugly
and if you have some problems with your api server and your not a backend i can fix it(if its django) or i can make a simple one for you to use

How to read the contents of a Post request on Postman?

In the systems I am testing, there are cases that the response informs 200 (ok), but the content may indicate an error in the internal validations of the backend service. How can I read the contents of the response with Postman and schedule a successful validation if this service error code comes as expected?
You can use the tests tab in Postman to run checks on the body (JSON and XML). There are snippets which show you the syntax. You can adapt them to check for the element of the response body which indicates the error.
Postman has a tab called "Tests" where you can provide you test script for execution.
If you want to validate your request responded with 200 OK, following is the script
pm.test("Status test", function () {
pm.response.to.have.status(200);
});
If you want to validate the response contains any specified string,
pm.test("Body matches string", function () {
pm.expect(pm.response.text()).to.include("string_you_want_to_search");
});
In your case am assuming the above script can be used. In case the response body is JSON,
pm.test("JSON Body match", function () {
var respBody = pm.response.json();
pm.expect(respBody.<json node>).is.to.equal("Error_name");
});
Example JSON response body
{
"id" : 100,
"status" : "Bad Request"
}
pm.test("JSON Body matches string", function () {
var respBody = pm.response.json();
pm.expect(respBody.status).is.to.equal("Bad Request");
});

json-server can we use other key instead of id for post and put request

I have fake api for testing in frontend side.
i have seen that id is required to put or post your data in json-server package, my question is can i use different key instead of id for ex.
{
id: 1, ---> i want to change this with my custom id
name: 'Test'
}
Let's see CLI options of json-server package:
$ json-server -h
...
--id, -i Set database id property (e.g. _id) [default: "id"]
...
Let's try to start json-server with new id called 'customId' (for example):
json-server --id customId testDb.json
Structure of testDb.json file: $ cat testDb.json
{
"messages": [
{
"customId": 1,
"description": "somedescription",
"body": "sometext"
}
]
}
Make a simple POST request via $.ajax function (or via Fiddler/Postman/etc.). Content-type of request should be set to application/json - explanation may be found on this project's github page:
A POST, PUT or PATCH request should include a Content-Type: application/json header to use the JSON in the request body. Otherwise it will result in a 200 OK but without changes being made to the data.
So... Make a request from Browser:
$.ajax({
type: "POST",
url: 'http://127.0.0.1:3000/messages/',
data: {body: 'body', description: 'description'},
success: resp => console.log(resp),
dataType: 'json'
});
Go to testDb and see the results. New chunk added. id automatically added with the desired name specified in --id key of console cmd.
{
"body": "body",
"description": "description",
"customId": 12
}
Voila!
I've came up with using custom routes in cases where I need custom id:
json-server --watch db.json --routes routes.json
routes.json:
{ "/customIDroute/:cusomID" : "/customIDroute?cusomID=:cusomID" }
If you start your server using a server.js file (read more about it in the docs), you can define custom ID routes in server.js like this
// server.js
const jsonServer = require('json-server')
const server = jsonServer.create()
const router = jsonServer.router('db.json')
const middlewares = jsonServer.defaults()
server.use(middlewares)
// custom routes
server.use(jsonServer.rewriter({
"/route/:id": "/route?customId=:id"
}))
server.use(router)
server.listen(3000, () => {
console.log('JSON Server is running')
})
And you would start your server with command:
node server.js
Internaly getById from lodash-id is used.
If you use file-based server version the equivalent to cli --id, -i
is router.db._.id = "customId";
If you want to do per resource, you can do it with a middleware like this (put before others):
server.use((req, res, next) => {
if (req.url.includes("/resourceName/")) {
router.db._.id = "code";
} else {
router.db._.id = "pk";
}
next();
});

header Content-Type case sensitivity issue in testing with superagent and jasmine-ajax

I'm using superagent and jasmine-ajax in my testing environment (karma with jasmine adapter).
I noticed an issue pertaining to case-sensitivity on the response headers when trying to mock responses that superagent will then handle.
Testing code:
it('should parse the response as json', function() {
var response = '{ "foo" : "bar" }';
superagent.get('/some/url', function(
expect(response.body).toEqual({ foo: "bar" });
});
jasmine.Ajax.requests.mostRecent().response({
status: 200,
// uncomment following line to make this test pass
// responseHeaders: { "content-type" : "application/json" },
responseText: response
});
});
In superagent.js line ~695 has:
this.header['content-type'] = this.xhr.getResponseHeader('content-type');
In mock-ajax.js line ~175 has
this.responseHeaders = response.responseHeaders ||
{"Content-type": response.contentType || "application/json" };
So, obviously within each respective library, there is a discrepancy with casing, but, according to spec, all the research I've done says that this field is case-insensitive. I thought that it might be an issue with PhantomJS, but I just tried using Chrome as well, but the same issue is present.
Any insight would be appreciated.