Render React JS component with Javascript - asp.net

I am using javascript to render React Component.
Javascript snippet
function loadRemoteComponent(url) {
return fetch(url)
.then(res => res.text())
.then(source => {
var exports = {}
function require(name) {
if (name == 'react') return React
else throw `You can't use modules other than "react" in remote component.`
}
const transformedSource = Babel.transform(source, {
presets: ['react', 'es2015', 'stage-2']
}).code
eval(transformedSource)
return exports.__esModule ? exports.default : exports
})
}
using URL, I am rendering React Component.
React component is rendered using Javascript with in current solution / web site.
When I tried to render the Javascript in different web site, it shows me CORS error.
I have tried "Access-Control-Allow-Origin"; but that is not working,
It shows me error in console
"Access to fetch at 'http://xxx/Scripts/components/xxx.jsx' from origin 'http://yyy' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled."
Do any one have any solution for this?

Have you tried setting the cors headers to wildcard on the server side?
// nodejs/express
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});

Related

How to force sails js csrf or login routes to always set response header set-cookie

I'm working with sails.js, trying to get it to always set the Set-Cookie response header for either the /csrfToken or /api/v1/entrance/login routes, so my React Native app can always dependably set the cookie in the app, and use it in all subsequent authorized requests. sails.js seems to only set it on the first call to /csrfToken from my app, but not on any of the rest, despite sending identical headers every time. Does anyone know how I can force sails.js to always respond with set-cookie on either of these routes?
You might use a hook for all the routes:
https://sailsjs.com/documentation/concepts/extending-sails/hooks/hook-specification/routes
module.exports = function (sails) {
return {
routes: {
before: {
'GET /*': function (req, res, next) {
// check req.headers.cookie
// set res.cookie()
return next();
}
},
}
}
req.cookies
https://sailsjs.com/documentation/reference/request-req/req-cookies#req-cookies
res.cookie()
https://sailsjs.com/documentation/reference/response-res/res-cookie#res-cookie-

Setting cache-control header for static file serving on nextjs default server

I am using the default nextjs server to run my nextjs program by this command next start.
However, I am not able to change the cache-control header for the files under the public folder.
Is there any method to set the cache-control header without setting the Custom Server?
There is undocumented feature or bug, but it works. More info can be found here https://nextjs.org/docs/api-reference/next.config.js/headers
Add config to you next.config.js file for example:
async headers() {
return [
{
source: '/:all*(svg|jpg|png)',
locale: false,
headers: [
{
key: 'Cache-Control',
value: 'public, max-age=9999999999, must-revalidate',
}
],
},
]
},
Per this bug report and discussion the Next devs believe static file serving should only be used as a developer convenience, not in production, and hence they don't consider it a priority to add such features.
However, in the issue comments somebody has suggested a workaround using Express to detect requests that will end up serving static files. For example, if the Next.js route handler is the handler() method you can do this to set a one-year cache policy for *.woff font files:
// this is a hack to make the cache headers friendlier..
server.get('*.woff2?', (req, res) => {
res.setHeader('Cache-Control', 'public,max-age=31536000');
return handler(req, res);
});
I'm using Express as a custom server for Next.js, and this is how I set "Cache-Control" header for static files:
const express = require("express");
const server = express();
...
server.use(express.static(__dirname + "/public", { maxAge: "365d" }));
server.use(function (req, res, next) {
if (req.url.match(".js|.css|.woff|.jpg|.png|.gif|.ttf")) {
res.setHeader("Cache-Control", "public,max-age=31536000"); // 365 days
}
next();
});

Angular5 Response Header (Content-Disposition) Reading

How Can I read Response Header (Content-Disposition)? Please share resolution.
When I check at either Postman or Google Chrome Network tab, I can see 'Content-Disposition' at the response headers section for the HTTP call, but NOT able to read the header parameter at Angular Code.
// Node - Server JS
app.get('/download', function (req, res) {
var file = __dirname + '/db.json';
res.set({
'Content-Type': 'text/plain',
'Content-Disposition': 'attachment; filename=' + req.body.filename
})
res.download(file); // Set disposition and send it.
});
// Angular5 Code
saveFile() {
const headers = new Headers();
headers.append('Accept', 'text/plain');
this.http.get('http://localhost:8090/download', { headers: headers })
.subscribe(
(response => this.saveToFileSystem(response))
);
}
private saveToFileSystem(response) {
const contentDispositionHeader: string = response.headers.get('Content-Disposition'); // <== Getting error here, Not able to read Response Headers
const parts: string[] = contentDispositionHeader.split(';');
const filename = parts[1].split('=')[1];
const blob = new Blob([response._body], { type: 'text/plain' });
saveAs(blob, filename);
}
I have found the solution to this issue. As per Access-Control-Expose-Headers, only default headers would be exposed.
In order to expose 'Content-Disposition', we need to set 'Access-Control-Expose-Headers' header property to either '*' (allow all) or 'Content-Disposition'.
// Node - Server JS
app.get('/download', function (req, res) {
var file = __dirname + '/db.json';
res.set({
'Content-Type': 'text/plain',
'Content-Disposition': 'attachment; filename=' + req.body.filename,
'Access-Control-Expose-Headers': 'Content-Disposition' // <== ** Solution **
})
res.download(file); // Set disposition and send it.
});
It is not the problem with Angular, is the problem with CORS.
If the server does not explicitly allow your code to read the headers, the browser don't allow to read them.
In the server you must add Access-Control-Expose-Headers in the response.
In the response it will be like Access-Control-Expose-Headers:<header_name>,
In asp.net core it can be added while setting up CORS in ConfigureServices method in startup.cs
this solution help me to get the Content-Disposition from response header.
(data)=>{ //the 'data' is response of file data with responseType: ResponseContentType.Blob.
let contentDisposition = data.headers.get('content-disposition');
}
Firstly you need to allow your server to expose these headers. Note that it will show in you browser network tab, regardless if you have these settings. This makes it 'available'.
With C# it would look something like this:
services.AddCors(options => {
options.AddPolicy(AllowSpecificOrigins,
builder => {
builder
.WithOrigins("http://localhost:4200")
.AllowAnyHeader()
.AllowAnyMethod()
.WithExposedHeaders("Content-Disposition", "downloadFileName");
});
});
When you send your API request to the server ensure that you include the "observe" in you return. See below:
getFile(path: string): Observable<any> {
// Create headers
let headers = new HttpHeaders();
// Create and return request
return this.http.get<Blob>(
`${environment.api_url}${path}`,
{ headers, observe: 'response', responseType: 'blob' as 'json' }
).pipe();
}
Then in your response of your angular on your subscribe you can access your filename like this (the subscribe method is not complete it attaches to a pipe function)
.....
.subscribe((response: HttpResponse<Blob>) => {
const fileName = response.headers.get('content-disposition')
.split(';')[1]
.split('filename')[1]
.split('=')[1]
.trim();
});

Angular 2 Http Get Request header issue

My Angular 2 Service is calling and external api , but i am getting a error in the browser console. I tried adding headers to the Get method but still the error persists.
Service
import { Injectable } from '#angular/core';
import { Http,Headers } from '#angular/http';
import 'rxjs/add/operator/map';
#Injectable()
export class CompetitionService{
constructor(private http:Http){
}
getCompetitions(){
let headers = new Headers();
headers.append('Access-Control-Allow-Credentials', 'true');
headers.append('Access-Control-Allow-Methods', 'GET');
headers.append('Access-Control-Allow-Origin', '*');
return this.http.get('http://api.football-data.org/v1/competitions',{headers:headers}).map(response => response.json())
}
}
console log Before Header
XMLHttpRequest cannot load
http://api.football-data.org/v1/competitions. No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:3000' is therefore not allowed
access.
After Header
XMLHttpRequest cannot load http://api.football-data.org/v1/competitions. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
this is CORS issue in browser and football-data api
http://api.football-data.org/docs/v1/index.html#_cors_handling
However, if you implement requests directly from Javascript, you need
to add your X-Auth-Token correctly so the API gives you permission to
do that
so to call api from your app, you need add header:
getCompetitions(){
let headers = new Headers();
let token = 'your token';
headers.append('X-Auth-Token', token);
return this.http.get('http://api.football-data.org/v1/competitions',{headers:headers}).map(response => response.json())
}

app.post on parse heroku server is unauthorized

I am trying to post to my server from twilio, but I am getting a 403 error. Basically my parse-heroku serve is rejecting any request from twilio. I am working with TWIMLAPP and masked numbers. I am having trouble posting to a function in my index file when a text goes through. In my TWIMLAPP my message url is https://parseserver.herokuapp.com/parse/index/sms Any help is appreciated. These are the errors in twilio
var app = express();
app.use(require('body-parser').urlencoded());
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'https://www.twilio.com');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
res.setHeader("X-Parse-Master-Key", "xxxxxxx");
res.setHeader("X-Parse-Application-Id", "xxxxxx");
// Pass to next layer of middleware
next();
});
app.post('/sms', twilio.webhook({ validate: false }), function (req, res) {
console.log("use-sms")
from = req.body.From;
to = req.body.To;
body = req.body.Body;
gatherOutgoingNumber(from, to)
.then(function (outgoingPhoneNumber) {
var twiml = new twilio.TwimlResponse();
twiml.message(body, { to: outgoingPhoneNumber });
res.type('text/xml');
res.send(twiml.toString());
});
});

Resources