How make request to MirajeJS js only when I need it - javascript

I have a fake server created with mirajeJs. All my requests are trying to contact him, how can I make a request for mirajeJs only in cases when I need it while making the rest of the requests to the real server

You can use a passthrough:
createServer({
routes() {
// Allow unhandled requests on the current domain to pass through
this.passthrough()
},
})
See MirageJS Passthrough documentation.

Related

How do I limit access to my Netlify Serverless function

I've searched the netlify docs and I can't figure this out.
I have a serverless function located here
/.netlify/functions/orderCreate
But I can hit this in my browser or with curl and it tries to create an order. If an attacker finds out about this function they could create thousands fake orders in my db.
I know I can do some simple checks like make sure it is a HTTP post, or make sure it has some valid session ID but I would really like some type of auth or better security.
Because all requests should come from the a client side react app via an ajax request can I limit it to the same domain or something ?
As Netlify doesn't provide a way to check and specific requests based on origin, you could do it manually from inside your function's code and send a 403 response if the Origin isn't your client-side domain:
exports.handler = function(event, context, callback) {
if (event.headers["Origin"] !== "https://whateverisyourdomainname.netlify.com")
return callback(null, { status: 403 })
// else, do whatever your function does
}
Recent browsers do prevent a user from setting the Origin header himself. However, nothing prevents anyone to craft a curl request and to spoof the Origin header to hit your function. If you wish to really prevent it, you should set-up a proper authentication process to your application.

Unable to call web-service from angularjs app

Unable to call post webservice from my application. following is the code.
var postLogin = "http://0.0.0.0:000/ddd/v1/login";
var loginvalue = {"email":"some#mail.com","password":"cbsjc6dw3bgjyfdgdKHGGDF="};
var config = {
headers: {
'Content-Type': 'application/json'
}
}
$http.post(postLogin ,loginvalue,config ).success( function(response) {
alert("response "+ response)
$scope.defer.resolve(response);
}).error(function(error){
alert("dddddd" + JSON.stringify(error));
})
If i write this code then it is returning as 400 error but if i use the postman application of google then i am getting the response without any error. So i am in confusion that whatever the code i have written is right or wrong. Hence i need to solve this issue.
Please go through the above image.
This usually happens when Client and Server are on different domains. The POST requests done by the client are first verified with a OPTIONS pre-flight check, to see if a POST would be possible. Sometimes, servers are configured to not allow OPTIONS request method. This will be the outcome of a pre-flight OPTIONS check, in such a case.
There is more information here - Why is an OPTIONS request sent and can I disable it?
Other resources for understanding the concept and helping us to configure the Response headers from the Server-side application are here:
https://medium.com/#praveen.beatle/avoiding-pre-flight-options-calls-on-cors-requests-baba9692c21a
https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
At the end of the day, if the Server is NOT configured to handle Cross-site requests, nothing can be done from the client-side.
Also, there are cases where the server does allow cross-site request, processes and send the response back to client, without the Access-Control-Allow-Origin header or with the Access-Control-Allow-Origin header, but not the same as the request origin or a wildcard "*". In such cases, browser stops processing the response, even when the call turns out to be in HTTP 200 OK Status.
Below is one such example, that I recently encountered while integrating with an external application.

CORS issue performing api calls in react/redux application

I was trying to implement a mailchimp api and came across a cross domain issue with an error in chrome like this:
XMLHttpRequest cannot load https://us9.api.mailchimp.com/3.0/members.
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://example.com' is therefore not allowed
access. The response had HTTP status code 501.
After some research it turns out that api calls I make are made from the browser (I simply call api from one of my actions), but to fix this issue they need to be made on the server.
Hence I am trying to figure out a way to call an api from the server inside of my action, to bypass this issue.
EDIT:
One of the solutions I found is to use jsonp for this, however I had to drop it as well, as I can't authenticate with it.
The solution I found is to proxy api calls through express in the following way:
In your express config:
import request from 'request'
app.use('/api', function (req, res) {
let url = 'your_api_url' + req.url
req.pipe(request(url)).pipe(res)
})
What this allows you to do is instead of calling https://myapi.com/endpoint in your components is to use /api/endpoint this way express will replace all instances of /api on your server with your api url and perform an api call from the server itself.

How to mock the API response with nightwatch.js and sinon.js?

I'm writing e2e test for a single page application with nightwatch.js.
I have some API request like an authentication. So I want to use fakeServer of sinon.js for mocking response data. Here's my code.
import sinon from 'sinon';
const WAIT_TIME = 5000;
const host = 'http://localhost:3000/#/';
const uri = new RegExp(escape('/users/login'));
module.exports = {
'Login Test': function(browser) {
let server;
browser
.windowSize('basicTest', 1440, 710)
.url(host + 'account/login')
.waitForElementVisible('body', WAIT_TIME)
.setValue('input[type=email]', 'sample#sample.com')
.setValue('input[type=password]', 'password')
.execute(function() {
server = sinon.fakeServer.create();
server.respondWith('POST', uri, [
200, { 'Content-Type': 'application/json' }, JSON.stringify(someResponseData),
]);
})
.submitForm('form')
.execute(function() {
server.respond();
})
.waitForElementNotPresent('input.[type=submit]', WAIT_TIME) // the page should be redirected to another page
.execute(function() {
server.restore();
server = null;
})
.end();
},
};
I can't mock response, and got the error below (When the API serve is running, got no error, but the response won't be mocked one).
Error: Origin is not allowed by Access-Control-Allow-Origin
I want to know, first of all, is it correct way to use sinon.js's fakeServer? And is that possible on e2e(and nightwatch.js)?
Please give me a help.
To answer your question I first need to explain the nature of the error you receive.
That's a CORS (cross origin resource sharing) error.
Basically, some service behind your single page app knows not to allow requests which don't originate from your app. The service returning that error (I can't tell what it is from the information you've posted) detects a request coming from not your app, and rejects it.
You could disable the CORS security of the service (I highly recommend you don't do this) or you could attempt to change the origin header of the request. This is tricky, as most modern browsers specifically prevent this change in order to protect users. Since you are using Nightwatch, your environment will, in general, be that of a browser.
Based on this error you must have set up the server incorrectly because it seems as if your request is still hitting your actual API and not the mocked server.
Probably because you when submit the form, the browser will still submit the form to where it is supposed to go (and not your mock server) unless it is told otherwise. Looking at your code, you are setting up a mock server, but from this file alone it is not clear how the browser is supposed to know to send requests to that mocked server.
See nock for an alternative solution, I'm about to start using it :)

How to send user token with every JsonP request?

In my sencha touch 2.1, after successful login a token is sent back from service which has to be stored and used with all future service calls. Since I am dealing with remote web service so all the stores use JsonP proxy to fetch data which is why I want to add the token to all such calls. Since JsonP doesn't support headers I am planning to add this token as url param but I am not sure how to do this for all JsonP calls originating from app.
A similar question for AJAX calls was found
Send user details (session token) within every AJAX requests (Sencha Touch 2)
but since JsonP does not support 'beforerequest' event and headers, I am stuck.
Is there any other event I can listen/intercept to add this url param? is there a way to write base proxy class which has this functionality? Please share some examples if you know how to do this.
Ok, I found a way that worked for me.
I extended JsonP proxy and in buildUrl method I appended cached token, and now I an using this proxy in all my stores. Here is the code:
Ext.define('myshop.proxy.CustomJsonpProxy', {
extend: 'Ext.data.proxy.JsonP',
alias: 'proxy.customjsonpproxy',
buildUrl: function(request) {
var me = this,
url = me.callParent(arguments);
if(!Ext.isEmpty(loggedInUserToken)){
url = Ext.urlAppend(url, "token="+loggedInUserToken);
}
return url;
}
});
Please share if you know of other better ways.

Categories

Resources