using the WiFlyHQ library i try to send an POST request, it seems like the request header get cropped, if i inspect the request on the server i can see the following:
headers: { host: 'localhost:3000', 'content-type': 'application' },
with this setup;
void SendJasonPacket()
{
wifly.open(Server, ServerPort);
wifly.println("POST / HTTP/1.1");
wifly.println("Host: localhost:3000");
wifly.println("Content-type: application/json");
wifly.println("Accept: application/json");
wifly.println("Content-Length: 93");
wifly.println("User-Agent: easyNAM/0.0.1");
wifly.println("{'checkin':{'device_token': '122','card_token': '12312', 'timestamp': '2012-10-29T14:31:03'}}");
wifly.close();
}
i tried a couple of different headers, that's what i got:
headers: { 'user-agent': 'easyNAM/0.0.1', accept: 'application/j' },
headers: { accept: 'application/json', 'user-agent': 'easyNAM/0' },
headers: { host: 'localhost:3000', 'content-type': 'application' },
it seems, that it get cropped after a specific character count, not sure what i did wrong here....
I believe memory is the issue, i ran into the same issue. I am using VS 2012 to build my app and when it reaches 60% it tends to act sporadically.
Related
I’m calling a service using a token
Failed to load resource: the server responded with a status of 401 (Unauthorized)
Http failure response for http://localhost:65291/api/post: 401 Unauthorized
The same call works in Postman with Headers;
Content-Type: application/json
Authorization: Bearer token
The function in ionic is
getPosts() {
var header = new HttpHeaders({ "Content-Type": "application/json" });
header.append("Authorization", "Bearer " + this.token);
console.log("Bearer " + this.token);
return new Promise(resolve => {
console.log(this.apiUrl + '/post');
this.http.get(this.apiUrl + '/post', { headers: header}).subscribe((data: Post[]) => {
resolve(data);
}, err => {
console.log(err);
});
});
}
Added a log for the token to be sure that is adding it to the header correctly (the token is fine).
The apiUrl variable has value http://localhost:65291/api.
What is wrong here? Cors is enabled… Postman works ok…
Thanks
I think you definitely have client side problem (since its 401 and also you mention Postman works ok).
I had similar issues when I tried to append headers in the same fashion you did so I would suggest trying this (to eliminate this problem):
getPosts() {
// try forming headers object in one go:
let token = "Bearer "+this.token
let headers = new HttpHeaders({
"Content-Type": "application/json",
"Authorization": token
});
// now here I am not sure why you do promise wrapping this way, but then I would suggest:
return this.http.get(this.apiUrl + '/post', { headers: headers })
.toPromise()
.then((data: Post[]) => { // Success
console.log(data);
resolve(data);
}, (err) => {
console.log(err);
});
}
If the problem is still there - please share which version of Angular and Http module you are using?
Also check out this issue here: How to correctly set Http Request Header in Angular 2
And specifically this answer if you are on Angular 4.3+:
How to correctly set Http Request Header in Angular 2
After a while I found the problem,
header.append("Authorization", "Bearer " + this.token); is wrong. It worked using
let headers = new HttpHeaders({"Authorization: " + "Bearer " + this.token})
Setting multiple headers:
this.http
.post('api/items/add', body, {
headers: new HttpHeaders({
'Authorization': 'my-auth-token',
'x-header': 'x-value'
})
}).subscribe()
I had a similar problem, it works on postman and cors enabled but in the app doesn't work, my problem was i have / at the end of the URL in the API security config, and i was making the request without /, i just remove it from request URL,
also you can add /* in security config or put / in your app, the URL must be the same.
(maybe you have solved your issue and it was different issue but this is a possibe solution)
I am working on simple web app on port 4000 with a RESTful API on port 8080. I have Express setup with the cors package and I seem to be sending the correct headers back from an OPTIONS request, see below:
X-Powered-By: Express
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET,HEAD,PUT,PATCH,POST,DELETE
Vary: Access-Control-Request-Headers
Access-Control-Allow-Headers: content-type
Content-Length: 0
This is returned with a status 204 ok. Then I see the PUT request in FF Network console and after about 45 secs the request header appears:
PUT /movies/updatemovie/59f4ee92be4becd967a573ca HTTP/1.1
Host: localhost:8080
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0
Accept: application/json, text/javascript, */*; q=0.01
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/json
Referer: http://localhost:4000/movies
Content-Length: 151
Origin: http://localhost:4000
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
The request parameters are:
documentID=59f4ee92be4becd967a573ca&title=Captain%20America%3A%20Civil%20UnWar&release=2016&score=9&reviewer=%20Janet%20Garcia&publication=%20MoviesNow
Chrome shows the PUT as having failed after 4mins.
The Data is not getting posted to Mongo, nor do I get any response from the server.
Here is the relevant code:
Web App
$(".panel").each(function (index) {
if ($(this).find("input[name = 'update']").is(":checked")) {
updatedDocument = {
documentID: $(this).data("id"),
title: $(this).find("input#name").val(),
release: $(this).find("input#release").val(),
score: $(this).find("input#score").val(),
reviewer: $(this).find("input#reviewer").val(),
publication: $(this).find("input#publication").val()
};
JSON.stringify(updatedDocument);
console.log(Object.values(updatedDocument));
} // end if
}); // .each
// Now we have the document stored in JSON object, so lets form
// an AJAX req and grab the updated data from our document and send
// a PUT to our API endpoint
$.ajax({
type: 'PUT',
data: updatedDocument,
url: 'http://localhost:8080/movies/updatemovie/' + updatedDocument.documentID,
dataType: 'JSON',
contentType: 'application/json'
}).done(function (response) {
// Check for successful (blank) response
if (response.msg === '') {
// do nothing
}
else {
alert('Error: ' + response.msg);
}
}); // end .done
API
/*
* Put to Update movie.
*/
router.options('updatemovie/:id', cors());
router.put('/updatemovie/:id', cors(), function(req, res) {
const db = req.db;
console.log(req.params.id);
console.log(req.body.publication);
const movieCollection = db.get("movies");
const movieToUpdate = req.params.id; // Assign collection document id from url :id value
const movieTitle = req.body.title;
const movieRelease = req.body.release;
const movieScore = req.body.score;
const movieReviewer = req.body.reviewer;
const moviePublication = req.body.publication;
// Update the movie document from PUT info
movieCollection.update({'_id' : movieToUpdate},
{
$set: {
title: movieTitle,
release: movieRelease,
score: movieScore,
reviewer: movieReviewer,
publication: moviePublication
}
},
function(err) {
res.send((err === null) ? {msg: ''} : {msg: err});
}); // movieCollection .update
});
I get nothing from the console.logs in the API. Any suggestions most welcomed.
UPDATE: By removing line from APP contentType: application/JSON everything now works. I thought I wanted to send data as JSON to my API? Anybody who has any thoughts or input most welcome.
You aren't sending the data as JSON. You've set the content-type header to application/json but the data will still be encoded as application/x-www-form-urlencoded. To send JSON data using jQuery you'd need to encode it yourself:
data: JSON.stringify(updatedDocument),
On the server you'd then need a suitable bodyParser configuration:
app.use(bodyParser.json());
or:
app.use(express.json());
When you removed the line contentType: 'application/json' that header fell back to its default value of application/x-www-form-urlencoded. That matches the format of the data and presumably you have app.use(bodyParser.urlencoded()) or app.use(express.urlencoded()) configured to parse that data. As your data is a flat string/string data structure it doesn't really matter which format you choose, you'll end up with the same values in res.body.
I don't manage to read response headers using browser_client.dart :
import 'package:http/browser_client.dart';
var response =
await client.post(url, headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}, body: body);
print('Response headers: ${response.headers}');
Thanks for your help.
The server needs to allow the browser to expose the headers by listing the headers in the Access-control-expose-headers response header, otherwise you can see them in the browser devtools but when you try to read them in code, the browser will suppress them.
See also
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
Why is Access-Control-Expose-Headers needed?
This Meteor server code uses atmosphere HTTP package. I receive human un readable characters from response.content even though characters are readable fine in the browser.
Why and how to fix that? Thanks
const response = HTTP.call(method, url, {
timeout: 30000,
headers: header,
params: Params,
followRedirects: true
}
);
console.log(response.content);
response header has:
'content-type': 'text/html'
'content-encoding': 'gzip'
request header has:
"Accept-Encoding": "gzip, deflate",
"Accept-Language": "en-US,en;q=0.5",
"Content-Type": "application/x-www-form-urlencoded"
I have a meteor method which uses HTTP.get to make a request to an API. From what I understood from the docs I can provide options with a headers object to set various things like Content-Type. I've tried this with the following code:
var r = HTTP.call("GET", apiUrl, { headers: { "Content-Type": "application/json" } });
console.log(r);
But this doesn't seem to work, the content type is till "text", see output below:
I20160302-13:50:22.706(0)? headers:
I20160302-13:50:22.706(0)? { 'access-control-allow-headers': 'Content-Type, api_key, Authorization',
I20160302-13:50:22.707(0)? 'access-control-allow-methods': 'GET',
I20160302-13:50:22.707(0)? 'access-control-allow-origin': '*',
I20160302-13:50:22.707(0)? 'content-type': 'text/plain; charset=utf-8',
I20160302-13:50:22.707(0)? date: 'Wed, 02 Mar 2016 13:50:20 GMT',
I20160302-13:50:22.707(0)? server: 'nginx/1.6.2',
I20160302-13:50:22.707(0)? 'content-length': '267',
I20160302-13:50:22.707(0)? connection: 'keep-alive' },
I've tried switching this about using "content-type" and "Content-Type". I've also tried using the shortened HTTP.get function