How can I set parameter in JSON request header? - json

I would like to set the userId and Password in JSON request header and remaining parameters in JSON request body. Can any give an example how can i set the userId/password in JSON request header and others parameter in JSON request Body.
Thanks in advance.

use Jquery:
<script>
//submit request
$.post('url',{userId: userIdvalue, Password: password value,...},function(response){
// do something when request processed successfully
});
//if you submit a form
$.post('url',{$("#formId".serialize())},function(response){
// do something when request processed successfully
});
</script>

Related

How to remove cookie param in request header for a post request in angular 6

When sending a post request cookie param is getting set in request header.
Is there any way to stop sending cookie param in api request header for a particular api call in angular interceptor
http module by default does not set the cookie params. When you get the response, http module discards the cookie and does not add it in the follow up requests. So you have add it manually:
checkAuth() {
// if we did not add { withCredentials: true }, response would be false becasue, cookies wont be attached
return this.http.get<SignedinResponse>(this.rootUrl + '/signedin',{withCredentials:true}).pipe(
tap(({ authenticated }) => {
// console.log('response from /signedin', res);
})
);
}
you have to add {withCredentials:true} this to each request manually. instead we write interceptor, to modify the req obj and add the cookie by default.

Node-red - Posting data to influxdb via http

Im trying to post data to an Influxdb via Node-red.
Via CURL i can post this:
curl -i -XPOST 'http://localhost:8086/write?db=waterlevel' --data-binary 'vattenstand,lake=siljan,region=dalarna value=160.80'
and it puts data to InfluxDb.
When I try to post via Node-red and an HTTP request I get the error:
{"error":"unable to parse '{\"url\":\"http://192.168.1.116:8086/write?db=waterlevel\",\"method\":\"POST\",\"body\":\"vattenstand,lake=siljan,region=dalarna value=160.80\",}': missing tag value"}
I use this code in a function in Node-red and pass it to the HTTP request:
var dataString = 'vattenstand,lake=siljan,region=dalarna value=160.80';
msg.payload = {
'url': 'http://192.168.1.116:8086/write?db=waterlevel',
'method': 'POST',
'body': dataString,
};
msg.headers = {
Accept: "application/json"
};
return msg;
The sidebar help for the node details the msg properties you should be setting to configure the node.
You are passing in URL, method and body as properties of msg.payload. That is not correct.
They should be set as msg.url, msg.method for the first two, and msg.payload should be the body of the request.
In this instance, you have already configured the node with a URL and method directly, so there's no need to pass them in with the message. In fact, as you have configured the URL in the node you will find you cannot override it with msg.url. if you want to set the URL with each message, you must leave the node's URL field blank in the editor.
You may also need to set the content-type header.
Assuming you are happy to leave the URL and method hard coded in the node, you function should be something like:
msg.payload = 'vattenstand,lake=siljan,region=dalarna value=160.80';
msg.headers = {
Accept: "application/json"
};
msg.headers['Content-type'] = 'application/x-www-form-urlencoded';
return msg;
Why don't you use the spezial influxdb node?
https://flows.nodered.org/node/node-red-contrib-influxdb
Advantage: The http header need not be created. You can reuse the defined connection for other data.

Express res.status(200).json(...) only sending json message. How to retrieve status code?

After a successful creation of new item in my database I send:
res.status(201).json({message:"Successfully Registered"});
On my angular front end I am able to console.log(res) and receive:
{message: "Successfully Registered"}
1) How do I get the status code on the front end? res.status returns undefined. The only response I'm getting is the JSON.
2) What would be the best way to confirm successful desired api calls? For example, when I log in and credentials are correct, should I check for a 200 and then proceed? Or send a custom JSON message and check if the message for example says "Successful login" then proceed?
A little bit late, but another option is to include the status in the JSON object:
res.status(201).json({message: "Successfully Registered", status: 201})
Now you can check the status in the front end doing res.status and use this to proceed with another action.
1- You can do res.status(200).send("You message here");
2- I would say your best option when doing the login and authenticating credentials is to create a session as such
req.session.user = req.body.username //username is the name attribute of the textfield
and then redirect to any page you'd like/you can also set status to 200
res.status(200);
I'm not familiar with Angular, but looking at the docs:
See https://angular.io/api/http/Response
You'll need to do something like:
http
.request('example.com')
.subscribe(response => console.log(response.status));
Sure, checking for 200 is fine. Typically with a REST API (inferred from what you've shown), after a login you're given back a JWT along with 200 OK. And any subsequent API all with that JWT will also yield a 200 OK along with the response body which is usually JSON.
You should tell your angular http client that you want to get the response status. By default, angular deserialize the response body, but you can set request option.observe:'response' to do so.
postData(model: MyModel): Observable<HttpResponse<{status: string}>> {
return this.http.post<{status: string}>(
model, { observe: 'response' });
}
See https://angular.io/guide/http#reading-the-full-response for details.
PS: sending a { status: 'message' } is not very useful, you may return an { id } or even nothing.
res.status(200).json({
status: 'success',
results: tours.length,
data:{
tour:tours
}
});
Usually, Jsend is a good choice to response, and also by convention. Absolutely you can see the 'status' in response data and the actually data you want in the data.
according to the angular guide, we can add observe in the options of our request.
getforgetpassword(email: string): Observable<any> {
const url = this.gatewayUrl + `newPasswordFor/${email}`;
return this.http.get(url, {observe: "response"});
}
using observe type as response will give total response along with request status, which you can use in your logic of controller.

NodeJs, Express, BodyParse and JSON

I'm trying to implement a simple server using Express 4.0 and parsing messages with BodyParser. To test my server I use Postman.
Using x-www-form-urlencoded as message mode it works with no problem but changing messages with JSON I can't parte data using BodyParse.
Here is my code:
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
var router = express.Router()
router.get('/', function (req, res){
res.json({message: "nd..."})
})
var sendRoute = router.route('/msg')
sendRoute.post(function(req, res){
// HERE IS THE PROBLEM******************************
// It works with urlencoded request but not with JSON
var dataparam1 = req.body.param1
var dataparam2 = req.body.param2
****************************************************
.
.
.
})
and let's say this is the JSON data I get form the request:
[{"param1":"This is the param1",
"param2":"This is the param2"
}]
What's wrong with my code? how can I get params sent with JSON format?
If your request body is sent as a JSON string, then you must tell your app that via a content-type header.
In Postman, click the Headers button, next to the drop-down to select the method and the URL params button. (Top right)
A table will expand, fill in Content-Type in the left field and application/json in the right field.
Submit the request.
bodyParser can handle multiple types of data, but it must know what format you're submitting. It will not attempt to guess the data type.
The drop-down menu (according to your comment, it's set to 'JSON' at the moment) just above the textarea where you fill in the request body only toggles syntax highlighting, it does not set the Content-Type header for you.

calling REST service on form submit

I am trying to call service http://localhost:8080/app/search It gets data in RequestBody as
{
"skills":["c","java"],
"country":["India"],
"state":["Maharashtra","Gujrat"],
"city":["Mumbai","Pune"],
"highestDegree":["MCA","BE"],
"functionalArea":["IT"],
"functionalRole":["Tester"]
}
and header Content-Type:application/json
I tested above service with Postman and it gives me correct output. Now i tried to call above service from html form its giving me error that request is syntactically incorect.
My HTML form is
<form method="POST" action="http://localhost:8080/app/search">
<!--(form ellements with multiple select textbox )-->
</form
Is it right way or I need model from backbone?
It's a wrong way, you have to create a Model and set it's url to your service :
var MyModel = Backbone.Model.extend({
url: '/app/search'
});
and when you click the submit button catch it in your view, set the form data in your model and call it's save function.