Unexpected token # in JSON at position 0 with Angular 5 and Express JS - angular5

I am developing a MEAN stack application
where My client is in Angular 5 and backend is in node and express js with mongo db as my storage.
I am trying to upload an image from one my Angular Page to my express js rest API which will finally upload the image in AWS cloud
Sample code for my Component is as below having two methods one onFileSelected which sets the selected file and the onUpload which invokes a service class method
private selectedFile:File=null;
onUpload(){
this.productCategoryService.
uploadProductCategoryImage(this.selectedFile).subscribe(
data=>{console.log("Upload success---"+data)},
err=>{console.log("Upload error ---"+err.message)});
}
onFileSelected(event){
this.selectedFile=event.target.files[0];
console.log("this.selectedFile---------"+this.selectedFile);
}
The service does a post call of rest service on express js.Code of my service class is as below
public uploadProductCategoryImage(selectedFile:File){
const formData = new FormData();
formData.append("userFile",selectedFile);
return this.http.post<any>
('http://localhost:3000/datastore/api/aws/api/file',formData);
}
My html page
<input type="file" (change)="onFileSelected($event)" name="userFile">
<button type="button" class="btn btn-success" (click)="onUpload()">
<span class="fa fa-upload"></span>Upload</button>
However when I post this data I get an error as below on the server side
SyntaxError: Unexpected token # in JSON at position 0
at JSON.parse (<anonymous>)
I found something from my browser.It shows BAD request.
I am not sure what is happening.Please suggest.
General------------
Request URL: http://localhost:3000/datastore/api/aws/api/file
Request Method: POST
Status Code: 400 Bad Request
Remote Address: [::1]:3000
Referrer Policy: no-referrer-when-downgrade
Response Header------------
Access-Control-Allow-Origin: *
Connection: keep-alive
Content-Length: 1314
Content-Security-Policy: default-src 'self'
Content-Type: text/html; charset=utf-8
Date: Fri, 22 Jun 2018 16:47:12 GMT
X-Content-Type-Options: nosniff
X-Powered-By: Express
Request Header--------------------
Accept: application/json
Accept-Encoding: gzip, deflate, br
Accept-Language: en-GB,en-US;q=0.9,en;q=0.8
Connection: keep-alive
Content-Length: 232378
Content-Type: application/json
Host: localhost:3000
Origin: http://localhost:4200
Referer: http://localhost:4200/contactus
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.62 Safari/537.36
------WebKitFormBoundaryAEgWhmyP5LdwDaEl
Content-Disposition: form-data; name="userFile"; filename="Screenshot from 2018-06-04 20-23-28.png"
Content-Type: image/png
Thanks
Sachin

In Angular 5 Httpclient uses JSON as default format. So you have use BLOB as your response type like
getImage(imageUrl: string): Observable<Blob> {
return this.httpClient.get(imageUrl, { responseType: 'blob' });
}
Check this link for reference: https://stackblitz.com/edit/angular-1yr75s?file=src%2Fapp%2Fimage.service.ts

Related

ASP.NET Core Cookie not set with CORS

I try to set a auth cookie. The ui and the data server are under different subdomains. So I need to activate CORS.
services.AddCors(options => options.AddPolicy("SubdomainDefault", builder => builder
.WithOrigins("https://ui.domain.de")
.AllowCredentials()
.AllowAnyHeader()
.Build()
));
On the same subdomain the cookie is set, but with different subdomains it is visible in the headers, but not set.
Request URL: https://server2.domain.de/...
Request Method: POST
Status Code: 200 OK
Remote Address: X.X.X.X:443
Referrer Policy: strict-origin-when-cross-origin
Response Header
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: https://ui.domain.de
Content-Length: 1017
Content-Type: application/json; charset=utf-8
Date: Fri, 29 Oct 2021 10:27:11 GMT
Server: Microsoft-IIS/8.5
Set-Cookie: auth=XXX; domain=.domain.de; path=/; secure; samesite=strict; httponly
Vary: Origin
X-Powered-By: ARR/3.0
Request Headers
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: de-DE,de;q=0.9,en;q=0.8,en-US;q=0.7
Cache-Control: no-cache
Connection: keep-alive
Content-Length: 0
Host: server2.domain.de
Origin: https://ui.domain.de
Pragma: no-cache
Referer: https://ui.domain.de/
sec-ch-ua: "Google Chrome";v="95", "Chromium";v="95", ";Not A Brand";v="99"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36
Has anyone a idea?
Assuming your second request is actually a XMLHttpRequest you need to set the withCredentials flag, otherwise the cookies are not sent.
Here's an excerpt from https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#requests_with_credentials:
const invocation = new XMLHttpRequest();
const url = 'https://bar.other/resources/credentialed-content/';
function callOtherDomain() {
if (invocation) {
invocation.open('GET', url, true);
invocation.withCredentials = true;
invocation.onreadystatechange = handler;
invocation.send();
}
}

.Net Core blocked by CORS policy error only when uploading a file

Is there something different that needs to be done when uploading a file? Every other call (Axios/Vue put) works fine except where a file is getting uploaded. It's going from example.com to api.example.com. Everything works fine locally hitting different ports.
ConfigureServices:
services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.SetIsOriginAllowedToAllowWildcardSubdomains();
//.WithOrigins("http://*.example.com"); //tried adding, nothing works when it's here
}));
Configure:
app.UseCors("CorsPolicy");
And the controller:
[ApiController]
[EnableCors("CorsPolicy")]
public class MyController : ControllerBase {
Public Model Put([FromForm] ICollection<IFormFile> files, [FromForm] string jsonString)
The browser output:
Access to XMLHttpRequest at 'http://api.example.com/api/YourKnowledge' from origin 'http://example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Request URL: http://api.example.com/api/YourKnowledge
Referrer Policy: strict-origin-when-cross-origin
Date: Sat, 03 Oct 2020 19:58:42 GMT
Server: Microsoft-IIS/10.0
Transfer-Encoding: chunked
X-Powered-By: ASP.NET
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Content-Length: 10219
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryvIG7idij6Og7BH8r
Host: api.example.com
Origin: http://example.com
Referer: http://example.com/
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
files: (binary)
jsonString:{}
Last note, I did find this Asp.Net Core API CORS policy error only in file upload, but I won't have just images uploaded. Did try setting it to test, but it didn't make a difference.
I think you couldn't add two parameter with [FromForm]
(I know that its the rule at least in [FromBody]).
please let me know that works

How to send a XMLHttpRequest

I want to send a request look like this:
POST /accounts/211242/followers HTTP/1.1
Host: website.com
User-Agent: <user-agent>
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: https://website.com
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With: XMLHttpRequest
Content-Length: 0
Connection: close
Cookie: <user-cookie>
But I don't know much about Javascript. I have tried a lot but everything I got just an error. Can anyone create a code for me?
Here what I have tried:
<html>
<head>
<title>CSRF Demo</title>
</head>
<body>
<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "https://website.com/accounts/211242/followers");
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
xmlhttp.withCredentials = true;
xmlhttp.send(null);
</script>
</body>
</html>
And after run that code, the browser sends a request:
POST /accounts/211242/followers HTTP/1.1
Host: website.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:68.0) Gecko/20100101 Firefox/68.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Origin: null
Connection: close
Cache-Control: max-age=0
Content-Length: 0
Cookie: <user-cookie>
Which don't have 'X-Requested-With: XMLHttpRequest' so the server sends back 400 Bad Request
According to the docs, you should add xmlhttp.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
after opening and before sending the request, to append the desired header.

Status code 415 although headers all seem to be correct

I have an API call on my front end application that uses Axios to make a PUT request. This works from postman but in the browser I get the 415 error. Here are the browser headers:
General
Request URL: api.example.com/foo
Request Method: OPTIONS
Status Code: 415 Unsupported Media Type
Remote Address: ip.address:443
Referrer Policy: no-referrer-when-downgrade
Response Headers
Access-Control-Allow-Headers: content-type
Access-Control-Allow-Methods: GET, PUT, POST, DELETE, HEAD, OPTIONS
Access-Control-Allow-Origin: *
Content-Length: 175
Content-Type: application/problem+json; charset=utf-8
Date: Mon, 13 Jan 2020 20:03:06 GMT
Request-Context: appId=guid
Server: Microsoft-IIS/10.0
Strict-Transport-Security: max-age=2592000
X-Powered-By: ASP.NET
Request Headers
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Access-Control-Request-Headers: content-type
Access-Control-Request-Method: PUT
Cache-Control: no-cache
Connection: keep-alive
Host: api.example.com
Origin: http://localhost:3000
Pragma: no-cache
Referer: http://localhost:3000/extension
Sec-Fetch-Mode: cors
Sec-Fetch-Site: cross-site
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36
My request looks like this:
const url = 'https://api.example.com/foo';
const headers = {
'Content-Type': 'application/json; charset=UTF-8'
};
const data = JSON.stringify([{"name": "SomeName","date": "2020-01-30T14:50:56.636Z"}]);
axios.put(
url,
data,
{headers: headers}
)
.then(res => {
console.log(res);
})
.catch((e) => {
console.log(e);
});
My API is a .net core application. Thank you friends!
I figured out the problem; in the API, the options handlers had some parameters (since I copy pasta'd the PUT request for options) and the browser wasn't sending the parameters in the preflight check, so I was getting 415. Once I removed the parameters, it worked fine!

axios send wrong csrf cookie

I want process a POST request with axios in a vuejs project, but axios never send correct csrf cookie. My vuejs project run in dev mode on port 8080, my server (Spring Boot) on port 9090. I set correct CORS filter for localhost:8080 and 127.0.0.1:8080, OPTIONS is accepted, but I get a 403 error on my POST.
Here my code :
axios.post("http://127.0.0.1:9090/api/security/authenticate",
this.form,
{
withCredentials: true,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN'
}
).then((response) => {
console.log("Data: " + response.data);
}).catch((error) => {
console.log("post error: " + error);
});
And here the result of my OPTIONS request on chromium :
GENERAL:
Request URL: http://127.0.0.1:9090/api/security/authenticate
Request Method: OPTIONS
Status Code: 200
Remote Address: 127.0.0.1:9090
Referrer Policy: no-referrer-when-downgrade
RESPONSE HEADERS :
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: content-type
Access-Control-Allow-Methods: POST
Access-Control-Allow-Origin: http://127.0.0.1:8080
Content-Length: 0
Date: Wed, 11 Dec 2019 21:44:07 GMT
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers
REQUEST HEADERS :
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7
Access-Control-Request-Headers: content-type
Access-Control-Request-Method: POST
Connection: keep-alive
Host: 127.0.0.1:9090
Origin: http://127.0.0.1:8080
Referer: http://127.0.0.1:8080/login
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) snap Chromium/78.0.3904.108 Chrome/78.0.3904.108 Safari/537.36
And my POST :
GENERAL:
Request URL: http://127.0.0.1:9090/api/security/authenticate
Request Method: POST
Status Code: 403
Remote Address: 127.0.0.1:9090
Referrer Policy: no-referrer-when-downgrade
RESPONSE HEADERS :
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: http://127.0.0.1:8080
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Content-Type: application/json;charset=UTF-8
Date: Wed, 11 Dec 2019 21:44:07 GMT
Expires: 0
Pragma: no-cache
Transfer-Encoding: chunked
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block
REQUEST HEADERS :
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7
Connection: keep-alive
Content-Length: 56
Content-Type: application/json;charset=UTF-8
Cookie: XSRF-TOKEN=428229a0-b2b1-4473-ab3a-557e4dbac1b1
Host: 127.0.0.1:9090
Origin: http://127.0.0.1:8080
Referer: http://127.0.0.1:8080/login
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) snap Chromium/78.0.3904.108 Chrome/78.0.3904.108 Safari/537.36
REQUEST PAYLOAD :
{login: "xxx", password: "xxx", rememberme: false}
login: "xxx"
password: "xxx"
rememberme: false
The CSRF cookie sent (428229a0...) is not correct. Previously in a GET request, I obtained an other CSRF token (70705d00...). Why wrong csrf cookie was sent ?
To be sure that is not the result of dev mode from vuejs, I build my project and deploy it on nginx server, but I got same result. I try also on firefox, get same error.
In package.json, axios is in version "^0.19.0", vuejs "^2.6.10".
What is wrong in my code ? Or is about configuration of my server ?
Thanks for your help!