How do I fix this JSON parsing issue? - html

I send data with fetch() in HTML to an express API, this is how it comes out in the req.body (I use body-parser)
{
'{"address":"a","town":"NYC","details":"a","appr":': { '"Car1"': '' }
}
it's all "stringy", as the only way I know to "parse it" to send it, is to send it with JSON.stringify. But, upon getting the info, it's "unparseable", JSON.parse errors with "unexpected string in JSON at position 62"
I send it like:
body: JSON.stringify({
address: address,
town: town,
details: details,
appr: apr,
}),
I've tried everything I know how to do to attempt to "make it a JSON" again, but nothing has worked.

1 - Don't forget to add header to fetch
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json' // => this is important
},
body: JSON.stringify(data)
});
2 - Don't forget to add this on express
app.use(bodyParser.json())
Note: If you are using Express v4.16.0 or newer you can use built-in middleware. Thanks to #Dov Rine
app.use(express.json());
3 - req.body will be available as object after this. You should not use JSON.parse(req.body) because body-parser does this for you.
let address = req.body.address;

Related

Angular failed post request with error 500

I am developing an ionic app that makes a rest call to a backend to send an email, when I make the rest call I get the following error, what can be due to (the rest call in postman works, I use chrome with the cors disabled)
Error:
POST http://172.16.50.92/send 500 (Internal Server Error)
Code Angular:
const params = {
'type': 'mail',
'attributes[to_recipients]': mail,
'attributes[body]': body,
'attributes[subject]': subject,
'attributes[attachments]': attachments
};
endpoint = url + '/send';
var headers_object = new HttpHeaders();
headers_object.append('contentType', 'application/json');
headers_object.append('Authorization', `Basic ${window.btoa(username + ':' + password)}`);
return this.http.post(endpoint, params, [headers_object]);
return this.http.post(endpoint, params, [headers_object]);
You put your headers into an array. But the signature is supposed to be
post(url: string, body: any, options: { headers: HttpHeaders })
for your usecase.
Please change to below and try again.
return this.http.post(endpoint, params, { headers: headers_object });

send post from webpage to Node.js server ...do not use 'fetch'...?

I am using the following javascript on a webpage to send information to a Node.js server upon a "click" on an image. This is using a 'POST' request.
<script>
function rerouter(_sent) {
var _people = <%- JSON.stringify(member_list) %>;
//convert the passed ('member_list') array into a JSON string...
var _attend = <%- JSON.stringify(online) %>;
//convert the passed ('online') array into a JSON string...
var splits = _sent.id.split("_"); //"split" on "underscore ('_')"
if (_people.indexOf(splits[1]) != -1) {
//**SEND INFO TO SERVER...
var available = _attend[_people.indexOf(splits[1])];
var response = fetch("members/pages/:" + splits[1] + "/presence/:" + available, {
method: 'POST',
headers: {
'Content-Type': 'text/plain;charset=utf-8'
}
});
//**
} //'_people' array contains the member name ('splits[1]')...
}
</script>
And here I handle the request in my Node.js server code:
var bodyParser = require('body-parser')
// create application/json parser
var jsonParser = bodyParser.json()
// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })
app.post('/members/pages/:membername/presence/:online', urlencodedParser, function (req, res) {
console.log("I RECEIVED FROM CLIENT THE FOLLOWING:")
console.log(req.params)
console.log(req.body)
res.redirect('/_landing');
})
Here is my console output:
I RECEIVED FROM CLIENT THE FOLLOWING:
{ membername: ':Nica', online: ':Yes' }
{}
As can be seen from my output, the POST route does seem to be functional, somewhat. However my 'redirect' command does NOT execute...the webpage does not change to the '_landing' page as it should...I think it may be because I am using 'fetch' to send the POST request...??? Can somebody verify if that is the cause (or another issue is the cause) and how I might be able to correct the issue?
In addition why does my 'params' include the colons (":") when I log to the console...is that standard? I would not think it would include the colons in the log, only the actual data.
Basically it seems my POST is almost working...but not exactly. Any suggestions would be greatly appreciated. I thank you in advance.
UPDATE: I have made some changes and my POST seems to be working fine now. In my frontend webpage I use the following to make the HTTP POST request:
<script>
function rerouter(_sent) {
var _people = <%- JSON.stringify(member_list) %>;
//convert the passed ('member_list') array into a JSON string...
var _attend = <%- JSON.stringify(online) %>;
//convert the passed ('online') array into a JSON string...
var splits = _sent.id.split("_"); //"split" on "underscore ('_')"
if (_people.indexOf(splits[1]) != -1) {
//**SEND INFO TO SERVER...
var available = _attend[_people.indexOf(splits[1])];
fetch('/members/pages/callup', {
method: 'post',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: JSON.stringify({name: splits[1], presence: available, str: 'Some string: &=&'})
})
//**
} //'_people' array contains the member name ('splits[1]')...
}
</script>
...And modified my route handler in my Node.js script:
// create application/json parser
var jsonParser = bodyParser.json()
app.post('/members/pages/callup', jsonParser, function (req, res) {
console.log("I RECEIVED FROM CLIENT THE FOLLOWING:")
console.log(req.body)
res.redirect('/_landing');
})
This is functional...to receive the data sent from the frontend webpage.
The only remaining problem is why does the 'redirect' not fire...??? I still have a feeling that by using a 'fetch' that somehow this is interfering with the page redirection...? A fetch would normally be used to wait for a response from the server, in my case I am not interested in that functionality I just want to send data one-way from frontend to backend...and then redirect the frontend page. I cannot think of any other reason why the redirect does not fire...?
Make extented:true instead of false as,
var urlencodedParser = bodyParser.urlencoded({ extended: true }) and move this line above of the below statement,
var jsonParser = bodyParser.json() and check if it works.
And finally change your headers here from,
headers: {
'Content-Type': 'text/plain;charset=utf-8'
}
To,
headers: {
'Content-Type': 'application/json'
}
Hope this will resolve the issue.

how to format an API call with access token in JavaScript

I can't figure out how to make a request with an access token from JS. I have the API documentation here: https://littlesis.org/api
I'm using P5.js as well
this.url = 'https://littlesis.org/api/entities/search?q=' + this.name;
httpDo(
this.url, {
method: 'GET',
// Other Request options, like special headers for apis
headers: {
'Littlesis-Api-Token': 'xxxxx'
}
},
function(res) {
println("!");
}
);
This doesn't seem to work, and it gives me the following error: "NetworkError when attempting to fetch resource."
Is there a way to simply place the access token in the URL? That way I can retrieve the JSON the old fashion way.
Try adding a no-cors option to your request:
this.url = 'https://littlesis.org/api/entities/search?q=' + this.name;
httpDo(
this.url, {
method: 'GET',
mode: 'no-cors',
// Other Request options, like special headers for apis
headers: {
'Littlesis-Api-Token': 'xxxxx'
}
},
function(res) {
println("!");
}
);
At least for me, this changes the error from a 422 unproccessable entity error to a 401 unauthorized error, which I assume your actual API key will resolve.

Angular HTTP post not accepting JSON response?

I created an API in laravel and tested in postman and it is working perfect. But when I try it from angular it works fine for returning a string text but not for JSON response
I searched it on internet and found setting content-type:application/json and tried with different ways for setting content type in header but issue still persist
var obj = JSON.parse('{"email":"ab#gm.com","password":"12345678"}');
//1st type of header
var headers_object = new HttpHeaders().set('Content-Type',
'application/json');
const httpOptions = {
headers: headers_object
};
//2nd type of header
var HTTPOptions = {
headers: new HttpHeaders({
'Accept':'application/json',
'Content-Type': 'application/json'
}),
'responseType': 'application/json' as 'json'
}
return this.http.post<any>(`http://127.0.0.1:8000/api/auth/login`, obj,HTTPOptions ).subscribe(resp => {
console.log(resp);
});
Postman Output
browser network request/response
return this.http.post(http://127.0.0.1:8000/api/auth/login, obj,HTTPOptions ).map((resp: Response) => resp.json())
hopefully this will work
Basically, you are sending "string JSON" instead JSON Object, send Javascript Object directly instead of string will solve your issue,
Use the below-mentioned way to post JSON data to the server,
var httpOptions = {
headers: new HttpHeaders({
'Accept':'application/json',
'Content-Type': 'application/json'
})
};
var dataToPost = {"email":"ab#gm.com","password":"12345678"};
this.http.post('http://127.0.0.1:8000/api/auth/login', dataToPost, httpOptions)
.subscribe(resp => {
console.log(resp);
});
It was due to CORB.
Cross-Origin Read Blocking (CORB) is an algorithm that can identify
and block dubious cross-origin resource loads in web browsers before
they reach the web page. CORB reduces the risk of leaking sensitive
data by keeping it further from cross-origin web pages.
https://www.chromestatus.com/feature/5629709824032768
Solution run chrome in disabled web security mode.
This worked for me https://stackoverflow.com/a/42086521/6687186
Win+R and paste
chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security

Easy way to Post HTTPS JSON data (header+body) using Node.js

After reading multiple internet posts related to "JSON POST commands" in NodeJS I'm now totally lost! Have tried to create an easy script to send data to a device Restful API interface using https. Without any luck...
JSON string needs to contain: a Header incl. (Basic)Auth Token & Body
content something similar like:
'{"address":address,"address6":"","comment":"","duids":[],"hostnames":[],"interface":""};
Hoping that someone has a good example available or can point me into right direction again.
You can use in-built module https to make a REST API call, the request signature is as follows:
https.request(url[, options][, callback])
In your case, you can try following code:
var options = {
host: 'host-name',
port: 443,
path: 'api-path',
method: 'POST',
// authentication headers
headers: {
'Authorization': 'Basic ' + new Buffer(username + ':' + passw).toString('base64')
}
};
const req = https.request(options, (res) => {
console.log('statusCode:', res.statusCode);
console.log('headers:', res.headers);
res.on('data', (d) => {
process.stdout.write(d);
});
});
I had the exact same issue just few days ago, and I've ended up creating a super tiny module called json-post.
const jsonPOST = require('json-post');
// or import jsonPOST from 'json-post'
jsonPOST(
'https://whatever:5000/seriously',
// your JSON data as object
{hello: 'world'},
// optionally any extra needed header
{'Authorization': 'Basic ' +
new Buffer(username + ':' + passw).toString('base64')}
).then(
console.info,
console.error
);
The dance is similar to the one shown in the previous reply but it's simplified in various ways. It works well for GitHub OAuth and others services too.
I always use request library whenever I need to do HTTP request in nodejs.
var request = require('request');
request({
method: 'POST',
uri: 'http://myuri.com',
headers: {
'Content-Type' : 'application/json',
'AnotherHeader' : 'anotherValue'
},
json: myjsonobj
}, (err, response, body) => {
// handler here
})
there are other ways of making the request as well like request.post() refer here