I'm trying to use a sentiment analysis API for some tweets I've streamed. The API in question is this: http://sentiment.vivekn.com/docs/api/. I've done this before in Python before and it worked as expected. I made a post request using the requests library and sent a JSON object with my content. The JSON object looked something like this:
{
"txt": "The content of the tweet."
}
In Python, sending the post request looked something like this:
url = "http://sentiment.vivekn.com/api/text/"
data_dict = {
"txt": "hi"
}
r = requests.post(url,json.loads(json.dumps(data_dict)))
print(r.text)
Now I'll admit I'm new to Javascript and web based programming in general, but I assume the logic should be similar in both languages. I tried using the XMLHttpRequest method but it always returned an internal server error with status code: 500.
The website works, it takes post requests and responds with the analysis, but I can't get it to work with Node. This is what I'm working with in Javascript:
const rp = require('request-promise');
var options = {
method: 'POST',
uri: 'http://sentiment.vivekn.com/api/text/',
body: {
"txt": "This is a very negative sentence, so we should get a negative analysis!"
},
json: true // Automatically stringifies the body to JSON
};
rp(options)
.then(function (parsedBody) {
console.log("Request received");
console.log(parsedBody);
})
.catch(function (err) {
console.log("Something went wrong\n" + err);
});
It always catches an error with status code 500. I've tried several other methods including making the request with XMLHttpRequest. Nothing seems to work. It would be great if someone could point out where I'm going wrong.
This isn't an answer, but I thought it useful to show some code that evokes a different response, which may be a clue that will help debug the problem.
I get the same response with curl:
jim-macbookpro:~/development/node/so$ curl -X POST 'http://sentiment.vivekn.com/api/text/' -H "Content-Type: application/json" -d '{"txt": "hi"}'
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>500 Internal Server Error</title>
<h1>Internal Server Error</h1>
<p>The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in theapplication.</p>
I changed the example to use 'node-fetch', and I don't get 500, rather I get 405 - METHOD NOT ALLOWED.
My suspicion is that this is a problem with the server being somehow very particular about the format of the request.
I hope this helps.
const fetch = require('node-fetch');
fetch('http://sentiment.vivekn.com/api/text', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
txt:
'This is a very negative sentence, so we should get a negative analysis!'
})
})
.then(function(parsedBody) {
console.log('Request received');
console.log(parsedBody);
})
.catch(function(err) {
console.log('Something went wrong\n' + err);
});
Related
I have below API for fetching all jobs on a project in gitlab:
fetch("https://git.nmlv.nml.com/api/v4/projects/project_id_here/jobs", {
method: 'GET',
headers: {
'Authorization': 'Basic my-token-here'
},
'Accept': 'application/json',
'mode': "no-cors"
})
.then(response => {
console.log("hello")
return response.text();
})
.then(
text => {
var result= JSON.parse(text);
console.log(text)
}).catch(err=>{
console.log(err);
})
The above request works fine in Postman with the same token but here it is saying that the request is unauthorized. The problem is on the Gitlab API docs, they haven't specified how the request in javascript should look like. for your reference, here is the API that I want to call. I know something is incorrect in the way I have framed the API's header. Can anyone help me to find how to frame the request correctly.
Thanks
EDIT
The problem now is that when I run same request on browser inside an html page, response is coming fine. But it is not working inside a node script. The control is not going to then or catch block.
I'm trying to integrate our website with Converge API with Hosted Payments Page. Here is the link to their documentation https://developer.elavon.com/#/api/eb6e9106-0172-4305-bc5a-b3ebe832f823.rcosoomi/versions/5180a9f2-741b-439c-bced-5c84a822f39b.rcosoomi/documents?converge-integration-guide/book/integration_methods/../../book/integration_methods/hosted_payments.html
I'm having troubles getting past the first step which is requesting a transaction token from their API endpoint. I'm sending a POST request from my server using axios with the correct parameters and URL, but when I try and POST i get 400 Bad Request. When I make the same request in POSTMAN I get a 200 response with the transaction token. I talked to their developers and they said that everything I was doing was correct and that nothing seemed odd within my code, so even they were stumped as to why I couldn't make a POST request to their endpoint. Obviously there is something within my code that their API is not liking, or else I wouldn't be here trying to find answers for this.
Here is how I'm making the POST request:
app.get('/converge_token_req', (request, response) => {
let params = {
ssl_merchant_id: '*****',
ssl_user_id: '*****',
ssl_pin: '*****',
ssl_transaction_type: 'ccsale',
ssl_amount: '1.00'
}
axios.post('https://api.demo.convergepay.com/hosted-payments/transaction_token', params, {
headers: { 'Content_Type' : 'application/x-www-form-urlencoded' }
}).then((res) => {
response.send(res.data)
}).catch((error) => {
console.log('there was an error getting transaction token')
response.send(error.message)
})
})
Here are the Request Headers:
I'm honestly out of ideas to try. The developers say that everything looks just fine yet I'm unable to make a successful request to their API. If anyone has any thoughts on this that would be great. Thanks!
This code below worked for me:
app.get('/converge_token_req', (request, response) => {
let params = {
ssl_merchant_id: '*****',
ssl_user_id: '*****',
ssl_pin: '*****',
ssl_transaction_type: 'ccsale',
ssl_amount: '1.00'
}
axios({
method: 'post',
url: 'https://api.demo.convergepay.com/hosted-payments/transaction_token',
params: params
}).then((res) => { response.send(res.data)
}).catch((error) => {
console.log('there was an error getting transaction token: ',
error)
})
})
I've since found out the solution to my problem. The issue here is that converge expects a x-www-form-urlencoded string that needs to be Stringified before submitting the request. I found a library that works well for this called qs and I used it like so:
let params = qs.stringify({ // need this if content_type is application/x-www-form-urlencoded
ssl_merchant_id: env.CONVERGE.MERCHANT_ID,
ssl_user_id: env.CONVERGE.USER_ID,
ssl_pin: env.CONVERGE.PIN,
ssl_transaction_type: request.query.type,
ssl_amount: request.query.amount,
ssl_email: request.query.email,
ssl_company: request.query.company,
ssl_avs_address: request.query.address,
ssl_avs_zip: request.query.zip,
ssl_description: request.query.desc,
})
axios.post('https://api.convergepay.com/hosted-payments/transaction_token', params, {
headers: {
'Content_Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
}
}).then((res) => {
response.send(res.data)
}).catch((error) => {
console.log('there was an error getting transaction token')
response.send(error.message)
})
I think you could also get away with just using JSON.stringify() but this way worked for me.
I'm performing a validation check on a Domain name entered by a user (eg.google.com) in my Nodejs back-end which will return either a good 200 response or bad 404 response if the domain entered was invalid.
In my React front-end I have the following code which sends the POST request:
const response = await
fetch('/new-cert', {
headers: {
'Content-Type': 'application/json'
},
method: 'POST',
body: JSON.stringify({domainInput: domainInputValue})
});
// Show error message if domain is invalid
if (!response.ok) {
this.setState({
validDomain: false
});
} else {
this.setState({
domainAdded: domainInputValue,
domainInputValue: '', // Clear input text
validDomain: true
});
}
However, my app is getting blocked and running really slow when it gets a 404 response, how do I correctly handle this error so that my app continues to run normally after I call setState?
I've tried some try-catch blocks but couldn't get them working.
I have some code to download a recording from Twilio
getRecordingMedia: function (recordingId) {
var client = new Twilio(config.twillio.apiKey, config.twillio.apiSecret, { accountSid: config.twillio.accountId });
var uri = `https://video.twilio.com/v1/Recordings/${recordingId}/Media`;
var response = client.request({ method: "POST", uri: uri });
var mediaLocation = JSON.parse(response.body).location;
request.get(mediaLocation, (err, res, media) => {
return media;
});
}
I get the following error:
SyntaxError: Unexpected token u in JSON at position 0
I looked at the response object and its actually a promise. So, it seems like the documentation is incorrect in the sense that it doesn't handle the promise "then()"
I went ahead and changed the code to use the promise
var response = client.request({ method: "POST", uri: uri }).then((object) => {console.log(object);});
And I actually have an error logged
{ statusCode: 405,
body: '{"code": 20004, "message": "Method not allowed", "more_info": "https://www.twilio.com/docs/errors/20004", "status": 405}' }
I looked at the documentation on the referred link, but it didn't help me much.
Additionally If I open the url https://video.twilio.com/v1/Recordings/${recordingId}/Media in my browser and enter the credentials I get the recording.
So, need help in figuring out if the documentation is incorrect (as to the promise - https://www.twilio.com/docs/api/video/recordings-resource#code-retrieve-a-recording) and why Im getting the error with code 20004.
Thanks
The explaination in the error link says it all. You are using the wrong request method.
The documentation says:
HTTP GET to /Media subresource
HTTP POST
Not supported.
Your code says:
var response = client.request({ method: "POST", uri: uri });
So of course it works in your browser, as browsers make GET requests...
My client posted data from one website to my website using npm request module.
ie as follows.
testservice : function(req , res){
var data = { title : 'my title' , content : 'my content'};
request.post('https://dev.example.com/test' , data , function(err , response ,body){
if (err) console.log(err);
if(response) console.log('statuscode='+response.statuscode);
});
};
I tried to get the JSON data posted to my site from my client's site using request get method , but i didnt get json data output.
Please help me out to get JSON data which is posted using request post method. Thanks.
Try this:
testservice: function(req, res) {
var data = { title: 'my title', content: 'my content' },
options = {
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
};
request.post('https://dev.example.com/test', options, function(err, response, body) {
if (err) console.log(err);
if (response) console.log('statuscode=' + response.statuscode);
});
};
I tried to get the JSON data posted to my site from my client's site using request get method, but i didnt get json data output.
I believe you may be misunderstanding the request.get function. It doesn't "get" the data that was posted to your site, it in fact fires a "get" request off to a particular URL.
If you want to receive data on your site that was POST'ed, then you need to configure your server to listen for POST requests from your friends site and then parse out the posted data from the body of that request.
i.e. in your server code if you're using raw node.js
http.createServer(function(req,res){
if(req.method.toUpperCase() === "POST"){
//code to parse out the data from the post request
}
}).listen(8080)
For more detailed info on parsing out the POST'ed data, see How do you extract POST data in Node.js?
Let me know if this helps, please clarify your question if not.