I'm trying to send a json to the backend, here is the piece of code that I use to send data:
register(user): Observable<any>{
let json = JSON.stringify(user);
let params = 'json='+json;
let headers = new HttpHeaders().set('Content-Type', 'aplication/x-www-form-urlencoded');
console.log(json);
console.log(params);
console.log(headers);
return this._http.post('http://api-rest-laravel.com.devel/api/register', params, {headers: headers});
}
This is the code in the backend:
public function register(Request $request) {
Log::info("Datos: " . $request);
$json = $request->input('json', null);
$params = json_decode($json);
$params_array = json_decode($json, true); //Array
Log::info("Json: " . $json);
if (!empty($params) && !empty($params_array)) {
//register
}else{
//send error msg
}
If i try the backend using Postman, this is what i get from Request param:
[2020-10-04 15:37:36] local.INFO: Datos: POST /api/register HTTP/1.1
Accept: */*
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Content-Length: 229
Content-Type: application/x-www-form-urlencoded
Cookie: laravel_session=eyJpdiI6InoxMG53RXZTTGZaV0h3dFF6VmVDUXc9PSIsInZhbHVlIjoiZ2V6ZEFYNjZKOSt0K0RPMmgra0FCMVUwMkhIb0JGSjJ6cW53VkhKSnUwV1ViWENVZTNDaXl3UzlBckZVYXRCSSIsIm1hYyI6ImM2YzA0MjEzYzRjMTEzNmQxYmY4NTJmNDRhNzk1ZGJmZGQwOGU2NmQ2NDM5OWM2MDcwNjFjNmJiMTIzNDIyM2MifQ%3D%3D
Host: api-rest-laravel.com.devel
Postman-Token: 47cfbc5a-136c-424d-9e1b-f61c18c2fc5c
User-Agent: PostmanRuntime/7.26.5
Cookie: laravel_session=pi7VHwGsyzTB36rK7KdbtAUU4GGagUNSklMQliqL
json=%7B%22id%22%3A1%2C%22name%22%3A%22qwer%22%2C%22surname%22%3A%22qwe%22%2C%22role%22%3A%22ROLE_USER%22%2C%22email%22%3A%22qqwer22%40asd.com%22%2C%22password%22%3A%22qqq%22%2C%22description%22%3A%22%22%2C%22image%22%3A%22%22%7D
[2020-10-04 15:37:36] local.INFO: Json: {"id":1,"name":"qwer","surname":"qwe","role":"ROLE_USER","email":"qqwer22#asd.com","password":"qqq","description":"","image":""}
[2020-10-04 15:37:36] local.INFO: goes toIF
and this is request param if I try it in browser ($json is empty, second last line):
[2020-10-04 15:40:30] local.INFO: Datos: POST /api/register HTTP/1.1
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate
Accept-Language: es-ES,es;q=0.9,en;q=0.8
Connection: keep-alive
Content-Length: 127
Content-Type: aplication/x-www-form-urlencoded
Dnt: 1
Host: api-rest-laravel.com.devel
Origin: http://localhost:4200
Referer: http://localhost:4200/
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36
json={"id":1,"name":"qwe","surname":"qwe","role":"ROLE_USER","email":"qqwe#asd.com","password":"q","description":"","image":""}
[2020-10-04 15:40:30] local.INFO: Json:
[2020-10-04 15:40:30] local.INFO: goes to ELSE
I also tried to send from frontend a json simillar to the one sent from postman to see if that was the problem. Didn't work.
//return this._http.post('http://api-rest-laravel.com.devel/api/register', 'json=%7B%22id%22%3A1%2C%22name%22%3A%22qwer%22%2C%22surname%22%3A%22qwe%22%2C%22role%22%3A%22ROLE_USER%22%2C%22email%22%3A%22qqwer222%40asd.com%22%2C%22password%22%3A%22qqq%22%2C%22description%22%3A%22%22%2C%22image%22%3A%22%22%7D', {headers: headers});
Why is this happening? I'm newbie with angular and laravel and I didnt find a solution so far. Corse is OK
in your header :
let headers = new HttpHeaders().set('Content-Type','application/json')
Related
I have the following setup:
Webserver 1 https://localhost:8888
Webserver 2 https://localhost:9005
Webserver 3 https://localhost:9006
I open https://localhost:8888 from a Web browser and enter the following JS code.
(async () => {
const endpointId = '1d60eb5195725648';
const continueUrl = 'https://localhost:9006/'
const signinUrl = new URL('https://localhost:9005/_login');
signinUrl.searchParams.set('continue', continueUrl);
signinUrl.searchParams.set('endpoint', endpointId);
const response = await fetch(signinUrl.toString(), {
credentials: 'include',
headers: {
'Authorization': `Bearer ${gapi.auth.getToken().access_token}`,
},
});
})();
I'm getting this error in my Chrome Browser Version 102.0.5005.115
Access to fetch at 'https://localhost:9006/?TOKEN=0<Truncated>c&endpoint=1d60eb5195725648' (redirected from 'https://localhost:9005/_login?continue=https%3A%2F%2Flocalhost%3A9006%2F&endpoint=1d60eb5195725648') from origin 'https://localhost:8888' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header has a value 'https://localhost:8888' that is not equal to the supplied origin. Have the server send the header with a valid value, or, if an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Looks like Origin field is correct according to the info in Headers. What am I missing?
(I truncated Token to improve readability)
Requests:
Request URL: https://localhost:9005/_login?continue=https%3A%2F%2Flocalhost%3A9006%2F&endpoint=1d60eb5195725648
Request Method: OPTIONS
Status Code: 200 OK
Remote Address: [::1]:9005
Referrer Policy: origin
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: Authorization
Access-Control-Allow-Headers: Proxy-Authorization
Access-Control-Allow-Methods: GET
Access-Control-Allow-Origin: https://localhost:8888
Content-Length: 0
Date: Sun, 12 Jun 2022 02:47:09 GMT
--
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9,es;q=0.8
Access-Control-Request-Headers: authorization
Access-Control-Request-Method: GET
Cache-Control: no-cache
Connection: keep-alive
Host: localhost:9005
Origin: https://localhost:8888
Pragma: no-cache
Referer: https://localhost:8888/
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36
Request URL: https://localhost:9005/_login?continue=https%3A%2F%2Flocalhost%3A9006%2F&endpoint=1d60eb5195725648
Request Method: GET
Status Code: 302 Found
Remote Address: [::1]:9005
Referrer Policy: origin
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: https://localhost:8888
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Content-Length: 360
Content-Type: text/html; charset=utf-8
Date: Sun, 12 Jun 2022 02:47:09 GMT
Expires: Mon, 01 Jan 1990 00:00:00 GMT
Location: https://localhost:9006/?TOKEN=00cfdab4e480656ed7d71b3e58df42fe5422d85d33118a5af5fb7cc66f2d81330b46740ccbca4927ecfe841e751f0de72fdf53c4eb7d66b7c5ab857e33c6beaa270950fe0c49047fd5260db3120731d0abbfe3be1a0d316db4b0754610c81e2b070cea24e46e0e5ef76937c65832ef7c315b452b846e87f59be3124478cee49045162c&endpoint=1d60eb5195725648
Pragma: no-cache
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9,es;q=0.8
Authorization: Bearer ya29.a0ARrdaM8mfOksOCl6l4O13z5PQv1cUVgKDKWgbo_rNXDL_Fw_-aedVVJdAFOSYByUjEy1WYrAKoik0KHx_c69aCXZcuAXbYedYkZRtDb5Y3Bz98eqjrOBjT0XrWspWdGNqRvsq_L_rDERdnsUFDFKCNiFCHV4sg
Cache-Control: no-cache
Connection: keep-alive
Cookie: _ga=GA1.1.1057744305.1654277711; _gid=GA1.1.1514740287.1654641546; _gat=1
Host: localhost:9005
Origin: https://localhost:8888
Pragma: no-cache
Referer: https://localhost:8888/
sec-ch-ua: " Not A;Brand";v="99", "Chromium";v="102", "Google Chrome";v="102"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "macOS"
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36
Request URL: https://localhost:9006/?TOKEN=00cfdab4e480656ed7d71b3e58df42fe5422d85d33118a5af5fb7cc66f2d81330b46740ccbca4927ecfe841e751f0de72fdf53c4eb7d66b7c5ab857e33c6beaa270950fe0c49047fd5260db3120731d0abbfe3be1a0d316db4b0754610c81e2b070cea24e46e0e5ef76937c65832ef7c315b452b846e87f59be3124478cee49045162c&endpoint=1d60eb5195725648
Referrer Policy: origin
Provisional headers are shown
Learn more
Referer: https://localhost:8888/
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36
I'm trying to upload binary file (to Amazon S3) from my localhost Vue page, using Amazon API Gateway with CORS enabled.
Actual POST Request have issued after Preflight Request issued.
And file upload have succeed.
But the POST Request have caught error bellow.
I don't know Why got the error?
Chrome(Version 79.0.3945.79)
got message
Access to XMLHttpRequest at 'https://XXXXXXXXXXX.execute-api.ap-northeast-1.amazonaws.com/dev/upload' from origin 'http://192.168.0.20:8080' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
AXIOS ERROR: Error: Network Error
at createError (createError.js?2d83:16)
at XMLHttpRequest.handleError (xhr.js?b50d:81)
Source code
async upload() {
console.log("file:", this.file);
const axiosConfig = {
headers: {
"Content-Type": "image/png"
}
};
axios
.post("https://XXXXXXXXXX.execute-api.ap-northeast-1.amazonaws.com/dev/upload", this.file, axiosConfig)
.then(res => {
console.log("RESPONSE RECEIVED: ", res);
})
.catch(err => {
console.log("AXIOS ERROR: ", err);
});
Header(Preflight Request)
Request
:authority: XXXXXXXXXX.execute-api.ap-northeast-1.amazonaws.com
:method: OPTIONS
:path: /dev/upload
:scheme: https
accept: */*
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9,ja;q=0.8
access-control-request-headers: content-type
access-control-request-method: POST
origin: http://192.168.0.20:8080
referer: http://192.168.0.20:8080/
sec-fetch-mode: cors
sec-fetch-site: cross-site
user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36
Response
access-control-allow-headers: Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token
access-control-allow-methods: DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT
access-control-allow-origin: *
content-length: 0
content-type: application/json
date: Fri, 13 Dec 2019 12:39:40 GMT
status: 200
via: 1.1 88c2e4442XXX3f0dXXX7df6fcXXX37ff.cloudfront.net (CloudFront)
x-amz-apigw-id: EpH19E9sNjMFhOg=
x-amz-cf-id: PEXXXH0x8_mlAspmv-xhi3X3XXXn_LSBswhXXXyqnCGZmVPkXXXYhw==
x-amz-cf-pop: NRT51-C1
x-amzn-requestid: 47XXc915-3b44-4XX7-959a-3XXX62150b3d
x-cache: Miss from cloudfront
Header(Actual POST)
Request
:authority: XXXXXXXXXX.execute-api.ap-northeast-1.amazonaws.com
:method: POST
:path: /dev/upload
:scheme: https
accept: application/json, text/plain, */*
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9,ja;q=0.8
content-length: 6849
content-type: image/png
origin: http://192.168.0.20:8080
referer: http://192.168.0.20:8080/
sec-fetch-mode: cors
sec-fetch-site: cross-site
user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36
Response
content-length: 47
content-type: application/json
date: Fri, 13 Dec 2019 12:39:40 GMT
status: 200
via: 1.1 88c2e44426XX3f0db837df6fc92437ff.cloudfront.net (CloudFront)
x-amz-apigw-id: EpH1_EeptjMFXqw=
x-amz-cf-id: XXqDis00oJqvh8wY-a0sugE6tuhwPHiJLs7ucXX5OdPC0uoCql7-nQ==
x-amz-cf-pop: NRT51-C1
x-amzn-requestid: 9XXX54a0-0a71-4cda-9d91-ae90a3322c9f
x-amzn-trace-id: Root=1-5XXX868c-fXXXa33dd82751efXXX547d;Sampled=0
x-cache: Miss from cloudfront
I solved it myself.
I don't know Why got the error?
Because Response header includes NO 'access-control-allow-origin'.
Browser could't read response body by CORB (Cross-Origin Read Blocking).
Added the header to response in Lambda function, it works.
s3.putObject({
Body: requestBody,
Bucket: "xxxxxx.com",
ContentType: "image/png",
Key: "uploadTest/logo.png"
})
.promise()
.then(result => {
const message = JSON.stringify(result);
callback(null, {
body: message,
statusCode: 200,
headers: {
"Access-Control-Allow-Origin": "*"
}
});
});
I am using swagger to post APi which works fine, but when I post it from react jsm that cause 405 issue.
Fiddler appears the RAW information for swagger as following:
POST http://localhost:7100/api/test/submit?guid=17327026-4348-4ce9-aceb-5774c3a724bf HTTP/1.1
Host: localhost:7100
Connection: keep-alive
Content-Length: 14
Origin: http://localhost:7100
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.78 Safari/537.36
Content-Type: application/json
Accept: */*
Referer: http://localhost:7100/swagger/ui/index
Accept-Encoding: gzip, deflate, br
Accept-Language: en,en-US;q=0.8,zh;q=0.6,zh-CN;q=0.4
Cookie: ASP.NET_SessionId=yzdydpdimqvgpvejykzjqqqb; .ASPXAUTH=dWLGc_XQvl3qTNrEJXsRyk3w-tXBSFeXKC0bIUDzLDLFJi5kbSAt_hcJXQs0-pfz7uVm-VJ27ZGAbN8eErCNV-Wozn3D1ZbHD7ONNN5VCMjT_Joyz_1aIcTZLR401s0TtC4Br1sRlerv0zX4F4xnDLhrIm5YKkGfZj2aZzDgc-KjNPVWY1SEC6k2XqPq54vo9_HUvudihHGlneNx1n2JlodvFxAeYudKnUSBRWpp2rRAx94uF7KmmP5BQoTmBTTq1qKSv98YiPToicePFR32d9yk1Uw1qcFrnkKD2zKOCuJByNgCLN_eC5dOmdLKfPCekciEJ16KfeYg8XeApIf13vCrtGOy-L2EXibWuEjUjKCrUy8sfYTGNZbxDffTg9gNOn7-nfyR5hKLYDM0CxfmENV7S0ExTSFyGhsR5aqqB3oXq3A_i8ENabgGMy_tFyor06S7_vrUUcDlS2hFgsxWzgMrRUdVIlohHK2-slPdbhwuUKIZXKKiSQijwH0RskwF-l8RyVe_0VCcCVipk4MXtncDvrubmEW09LWeOycyc0wc1BmMHL9AATpBHA6WBNLEaMGS9-x-RhFC5YNJW1KtetmlXiaKmiX9L-2wWhVRgjlhmfjtRPjxlVvW1GxyeKC-JOlSPnY6DInNM-qa2dcZjdaoffdnLBvzKTHkJNwzUSZw8fN-Vz6SVmURMtpEQAKmxloNvw
"test working"
for post from react as following:
OPTIONS http://localhost:7100/api/test/submit?guid=17327026-4348-4CE9-ACEB-5774C3A724BF HTTP/1.1
Host: localhost:7100
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Access-Control-Request-Method: POST
Origin: http://localhost:3000
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.78 Safari/537.36
Access-Control-Request-Headers: content-type
Accept: */*
Referer: http://localhost:3000/?testId=17327026-4348-4ce9-aceb-5774c3a724bf
Accept-Encoding: gzip, deflate, br
Accept-Language: en,en-US;q=0.8,zh;q=0.6,zh-CN;q=0.4
I believe something wrong in following fetch post function, is there any chance to fix it, then the RAW information can be same as first one.
onFormSubmit(Result) {
fetch("http://localhost:7100/api/test/submit?guid=" + "17327026-4348-4CE9-ACEB-5774C3A724BF",
{
method: 'POST',
// headers: {'Content-Type':'application/x-www-form-urlencoded'},
headers: {'Content-Type':'application/json'},
// contentType: 'application/json; charset=utf-8',
// body: JSON.stringify(result)
body: "test working"
})
.then((response) => {
console.log(response.ok ? 'success' : 'error');
})
.catch(function (error) {
console.log('catch error');
});
}
This is a CORS Issue You need to allow requests comming from http://localhost:3000 in you server.
PUT .../jobs/expenses/3434534534 HTTP/1.1
Host: ....com
Connection: keep-alive
Content-Length: 251
Accept: application/json
Origin: .....com
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36
Authorization: N/A
Content-Type: application/json
Referer: .....
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8
Cookie: .....
{"amount": 0, "timein": "11:11", "timeout": "12:11".....}
I have been working on getting this json body that is being sent (viewed with fiddler) but I am always getting an empty string.
Setting the following: HttpContext.Current.Request.InputStream.Position = 0 before trying to read the information still returns an empty string.
Various ways I've tried to extract this information
Dim myStream As Stream
myStream = HttpContext.Current.Request.InputStream
myStream.Position = 0
Dim myStreamReader As New StreamReader(myStream)
otherText = myStreamReader.ReadToEnd()
Dim bytes = New Byte(objRequest.InputStream.Length - 1) {}
objRequest.InputStream.Position = 0
objRequest.InputStream.Read(bytes, 0, bytes.Length)
otherText = System.Text.Encoding.Default.GetString(bytes)
How can I pull this information that I can view with fiddler, all avenues that I have explored has resulted with the same results. Empty string.
I'm trying to configure the wireless settings (like setting ssid as "vinoth" channel as "1") in Linksys EA4500 AP. I could see the below POST message using wireshark.
3E##!dPzY+2K
SPOST /JNAP/ HTTP/1.1
Host: 192.168.1.1
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:22.0) Gecko/20100101 Firefox/22.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/json; charset=UTF-8
X-JNAP-Action: http:cisco.com/jnap/core/Transaction
X-JNAP-Authorization: Basic YWRtaW46YWRtaW4=
X-Requested-With: XMLHttpRequest
Referer: http:/cisco.com/ <<<<==== routerip
Content-Length: 474
Cookie: initial-tab=; ui-proxy-path=local; admin-auth=Basic%20YWRtaW46YWRtaW4%3D; current-applet=7B1F462B-1A78-4AF6-8FBB-0C221703BEA4
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
[{"action":"http:/cisco.com/jnap/wirelessap/SetRadioSettings","request":{"radios":[{"radioID":"RADIO_2.4GHz","settings":{"isEnabled":true,"mode":"802.11bgn","ssid":"vinoth","broadcastSSID":true,"channelWidth":"Auto","channel":1,"security":"None"}}]}},{"action":"http://cisco.com/jnap/guestnetwork/SetGuestNetworkSettings","request":{"isGuestNetworkEnabled":false,"guestSSID":"vinoth-guest","guestPassword":"BeMyGuest","maxSimultaneousGuests":5,"broadcastGuestSSID":false}}]
I tried automating the above action using Perl but it didn't workout. As I am new to this JSON page I don't know how exactly the POST message to be sent.
content I kept for $json is
'{"action":"http:/cisco.com/jnap/wirelessap/SetRadioSettings",' .
'"request":{"radios":{"radioID":"RADIO_2.4GHz","settings":'.'{"isEnabled":true,"mode":"802.11bgn","ssid":"vinoth212","broadcastSSID":true,"channelWidth":"Auto","channel":1,"security":"None"}}}},{"action":"http://cisco.com/jnap/guestnetwork/SetGuestNetworkSettings",' .
'"request":{"isGuestNetworkEnabled":false,"guestSSID":"vinoth-guest","guestPassword":"BeMyGuest","maxSimultaneousGuests":5,"broadcastGuestSSID":false}}';
and the code:
use strict;
use warnings;
use LWP;
my $ua = LWP::UserAgent->new;
my $ip = $self->{ip};
my $url = "http://$ip/";
my $json = "";
my $req = HTTP::Request->new(POST=>$url);
$req->header('content-type' => 'application/json');
$req->authorization_basic("admin", "admin");
$req->content($json);
Below code for checking the request status
my $res = $ua->request($req);
if ($res->is_success) {
my $message = $res->decoded_content;
print "received the message";
} else {
print "HTTP get code: ", $res->code, "\n";
print "HTTP get: msg: ", $res->message, "\n";
}
Please help me in fixing this. Awaiting for your valuable reply.
P.S: In the Wireshark Post message the links are not proper as I am unable to post the query with more than 2 links.
Thanks,
Vinoth
Using the code $req->authorization_basic("admin", "admin"); it means Authorization: Basic YWRtaW46YWRtaW4= HTTP header when make any request.
But From your wireshirk's header it is X-JNAP-Authorization: Basic YWRtaW46YWRtaW4=, which is different thing(a custom header). So remove that authorization_basic from your block and use these ones:
$req->header('Content-Type' => 'application/json; charset=UTF-8');
$req->header('X-JNAP-Action' => 'http:cisco.com/jnap/core/Transaction');
$req->header('X-JNAP-Authorization' => 'Basic YWRtaW46YWRtaW4=');
## YWRtaW46YWRtaW4= is base64 of admin:admin
$req->header('X-Requested-With' => 'XMLHttpRequest');