Is there a difference between text/plain and string? - javascript

I am trying to send a Put request to an older Java back end. The path on the back end is
#PUT
#Path("/foo/bar")
#Consumes("text/plain")
public String someFunction(String ExpectedArgument){
//Unrelated logic
}
I'm trying to send a string from the front end using Javascript and Axios.
let someString = 'Example String'
axios.put('/foo/bar',someString).then(resp=>console.log(resp))
Unfortunately, when I try to do this, I'm receiving an HTTP 415 error for bad content type. Reviewing other, successful put requests that I've made, the only difference I've found is that this one has the "#Consumes("text/plain")" line in it. I can only conclude that there's some difference between what the java is expecting as text/plain and what I'm providing with a javascript string.
I would like to know what about my string is causing it to be rejected and how I can edit my code so that the back end will accept it.

const headers = {
'Content-Type': 'text/plain',
}
let someString = 'Example String'
axios.put('/foo/bar', someString, {
headers: headers
}).then(resp=>console.log(resp))

Related

How can I send new line feed in a POST call using plain text in JavaScript ES6 / Prometheus

I am trying to send a payload using POST to a Prometheus gateway server.
This server expects the request to be text/plain and it must end with a new line feed character.
"Using the Prometheus text protocol, pushing metrics is so easy that no separate CLI is provided. Simply use a command-line HTTP tool like curl. Your favorite scripting language has most likely some built-in HTTP capabilities you can leverage here as well.
Note that in the text protocol, each line has to end with a line-feed character (aka 'LF' or '\n'). Ending a line in other ways, e.g. with 'CR' aka '\r', 'CRLF' aka '\r\n', or just the end of the packet, will result in a protocol error."
var payload = 'http_requests_total{method="post", code="200"} 1000 1295000000000'
var apiRequest = http.request{{
'endpoint': 'http//myserver/api/metrics',
'method': 'POST',
'headers': {
'content-type': 'text/plain',
'Accept-Encoding': 'UTF-8'
}
)}
var resp = apiRequest.write(payload);
If I send as is, I receive a 400 response saying "unexpected end of input stream"
This is because the payload does not end with a line feed character.
I have tried to add "\n" but this doesn't work.
var payload = 'http_requests_total{method="post", code="200"} 1000 1295000000000' + '\n'
Am I missing something fundamental? If I send a curl request is works! but I am limited to using JavaScript ES6.

Javascript object coming through empty on server side

I have a client-side script running to send the string "Y" to the server. I set up a console.log on the client-side (which you can see below) and another on the server-side. The one on the client-side works, but the one logs an "empty" object.. it just shows "{}".
How do I get my data to stay in the object?
const status = "Y";
const options = {
method: 'POST',
headers: {
'Content-type': 'application/json'
},
body: status
fetch('/events/<%- event.id %>/prompt', options)
console.log(options.body)
Here's my route for context:
router.route('events/:id/prompt')
.get(catchAsync(events.showPrompt))
.post(catchAsync(events.checkIn))
And my controller:
module.exports.checkIn = async(req, res) => {
console.log(req.body);
}
How do I get the object to come through to the server?
For sending "y" as the content and receiving that in Express, you need two things:
You need to make sure the content-type is set to text/plain on the request.
You need the appropriate middleware that will read that text/plain body.
app.use(express.text())
Then, you will find the body in req.body within any express request handler registered after the above middleware.
You could pick different content-types also such as application/json, the corresponding middleware for that content-type app.use(express.json())` and then format the body data in that format.
It's important to realize that Express does not by itself read the body of an incoming request. It reads the headers, but not the body by default. If you want the body to be read, then you need middleware that is looking for whatever content-type the incoming request has, reads the body, parses it from whatever it's format is and puts the resulting parsed data into req.body. Express comes with a number of built-in middleware for popular content-types.
Status is a string. However body have to take a object with key-value pair. If send like with like below, then you get object which contains status on the backend side.
body: {status: status}
Problem from :
Client : you choose Content-type': 'application/json' , so your body must be json format , something like body : { status } . Make sure you sent exact object with browser debug , because some call api package can change value of request.
Server : Some nodejs framework need parse the value is sent from client before read it (Exp : app.use(express.json()) with Express)

Need to add value into my URL while doing HTTP post request using Google Cloud Function

I'm creating a OTP type of registration for my react native based mobile app. By using google cloud function to generate otp and post http request to my SMS provider.
The problem i am facing is that, whenever i try to add the random code to my sms provider url with ${code}, the message simply displays the same ${code} not the randomly generated code.
In other words, don't know how to interpolate the code into my url (as i am a newbie).
Here is my code for Random Number :
const code = Math.floor((Math.random() * 8999 + 1000));
And my request using request package is as follows:
const options = {
method: 'POST',
uri: 'http://smsprovider.com/numbers=${numbers}&route=2&message=Your OTP is ${code}',
body: {
numbers: phone,
code: code
},
json: true
};
So, whenever I get a message, it says Your OTP is ${code}. But what I actually need is to show the random number generated by the math.floor function. Expected "Your OTP is 5748"
Kindly guide
For string interpolation with JavaScript be sure to use the
`
character instead of
'
Try this instead:
const options = {
method: 'POST',
uri: `http://smsprovider.com/numbers=${numbers}&route=2&message=Your OTP is ${code}`,
body: {
numbers: phone,
code: code
},
json: true
};
String interpolation and url encoding are two distinct paradigms, one doesn't replace the other.
string interpolation allows you to dynamically insert a variable's content into a string with ${}. For this to work you must enclose your string between back quotes as #Ben Beck instructed. Some interpreters will be forgiving, meaning that even if you use single quotes, the interpreter will nonetheless parse the string with the interpolation, however not all interpreters do that, and it is bad practice to rely on it. Make sure you format these correctly.
url component encoding converts the url parameters containing special characters into a valid uri component with encodeURIComponent(). This is how you get rid of spaces and other special characters, however it might not be needed here as most browsers do that for you. Use Chrome to be sure, but again it is good practice to write fully portable code, I recommend to encode any parameter featuring any special character.
The fact that your Postman test failed is most certainly due to a faulty request. Check this screenshot for a working Postman POST request based on your case, leveraging Pre-request Script.
While testing with your code directly (not through Postman), if you keep getting the literal ${code} in place of the actual value, it likely means that the definition const code = Math.floor((Math.random() * 8999 + 1000)) is not in the same scope as the interpolation call. Check below for an example of working script using both string interpolation and url encoding based on your case:
const request = require('request');
const code = Math.floor((Math.random() * 8999 + 1000));
var p1 = encodeURIComponent(`Your OTP is ${code}`);
var uri = `http://smsprovider.com/?message=${p1}`;
const options = {
method: 'POST',
url: uri,
json: true
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
else {
console.log(error);
}
}
request(options, callback);
same but without url encoding and with the message parameter embedded in body element:
var uri = `http://smsprovider.com/`;
const options = {
method: 'POST',
url: uri,
body: {
message: `Your OTP is ${code}`,
},
json: true
};

Best way to replace left and right parenths in a Get request

For my GET request, my server is rejecting it with status: 403, "HTTP/1.1 403 Forbidden"
My GET request object as is follows :
"{"method":"GET","url":"api/myapi/GETstuff","params":{"from":"2017-06-02","to":"2017-06-02","myData":"DATA (AND SOME/MORE DATA)"}}"
The javascript code is:
function getMyData(params){
var url = 'myapi/getStuff';
var req = {
method: 'GET',
url: url,
params: params
};
$http(req) // details omitted for brevity
.success()
.error();
}
I believe the problem is special characters send to the IIS server (such as parenths, and / char), which I need to encode the params array before the GET request is sent via the Angular $http() service.
In order to encode the left/right parenths, and the / char, I'm trying:
request.params.myData = request.params.myData.replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\//g, '%2F')
However, my server is still rejecting the request.
And I doing something wrong?
You're getting a Forbidden error. Sure you don't need to authenticate or pass a token?
Before getting too manual, I'd suggest trying JSON.stringify(obj) and as a second pass, encodeURIComponent(obj)
If you're posting a valid JSON object, you might want to consider POST instead of GET, if you have backend access.

HTTP POST Request with JSON payload in Google Apps Script

I'm having trouble getting Google App Script's UrlFetchApp class to correctly format a JSON payload in a HTTP request.
Here's how I'm formatting the payload:
var data = {
'RequestData': {
'ItemNumber': '1',
'StockItemId': '2',
'ImageUrl': 'www.example.com'
}
};
var payload = JSON.stringify(data);
Surely enough, Logger.log(payload) returns:
{"RequestData":{"ItemNumber":"1","StockItemId":"2","ImageUrl":"www.example.com"}}
However, when I integrate this with the actual request:
var url = 'https://example.com/api/method';
var options = {
'method': 'post',
'contentType':'application/json',
'payload': payload,
'muteHttpExceptions': true
};
and examine Logger.log(UrlFetchApp.getRequest(url, options).toSource()), I get this:
({method:"post",
payload:"{\"RequestData\":{\"ItemNumber\":\"1\",\"StockItemId\":\"2\",\"ImageUrl\":\"www.example.com\"}}",
followRedirects:true,
validateHttpsCertificates:true,
useIntranet:false, contentType:"application/json",
url:"https://example.com/api/method"})
i.e. all the quotes are escaped, as if JSON.stringify is being called twice on the payload.
I thought GAS might be calling an equivalent of JSON.stringify on the payload behind the scenes because contentType is specified as "application/json" but if I pass the data raw without stringifying it, I get:
({method:"post",
payload:"RequestData=%7BItemNumber%3D1,+StockItemId%3D2,+ImageUrl%3Dwww.example.com%7D",
followRedirects:true,
validateHttpsCertificates:true,
useIntranet:false, contentType:"application/json",
url:"https://example.com/api/method"})
which is weird and (I'm pretty sure) an invalid JSON string. Either way, the request fails (400 Bad Request) and I'm pretty sure it's because I can't get the JSON across properly.
All the docs and examples I can find seem to suggest that JSON.stringify(payload) is the way to go but I'm clearly having issues...
Have also had the thought that this might have something to do with the implementation of the .toSource() method and that my problem might lie elsewhere but I have no way of knowing / otherwise being able to check the request body I'm sending.
Any insight would be much appreciated!

Categories

Resources