I would like to know the regular expression for fulfill the following pattern: - regex

I would like to know the regular expression fulfill the following pattern:
It will accept total 9 digits
After two digit there will be a dash
Not allowed all the zeroes
It should not start with zero
E.g. 12-2322232 --> valid 01-2323232 --> Not valid 00-0000000 --> Not valid

You can use axios, fetch which comes out of the box with React, superagent etc. Here I'll show you how to use axios for server calls:
$npm i -S axios
import axios from 'axios' // import inside the component you will make the request.
//Make the call function.
userDataCallHandler = () => {
axios({
method:'post',
url:'here the api url endpoint',
data:{
name:this.state.name,
password:this.state.password
},
headers:{
'Content-Type':'application/json'
Authorization:'your token if you need it'
}
})
.then(({data}) => {
consolo.log(data)
})
.catch(err => console.log(err));
Visit https://www.npmjs.com/package/axios for further info about it.

Related

Cypress setCookie not working as expected

I have added a command getCSRFToken that is used by other commands to get the CSRF token for making requests to my app:
Cypress.Commands.add("getCSRFToken", () => {
cy.getCookie('XSRF-TOKEN').then((cookie) => {
if (!cookie) {
return cy.request('HEAD', '/')
.its('headers')
.then((headers) => {
const token = headers['x-xsrf-token'];
if (!token) {
throw new Error('XSRF token not found');
}
return cy.setCookie('XSRF-TOKEN', token)
.then(() => token);
});
}
return cookie.value;
});
});
The portion that makes a HEAD request is for usage of this function when no pages have yet been visited in the test, for example when making POST requests to create test data.
AFAICT this looks like it should work to me, however it seems subsequent calls to getCookie doesn't actually retrieve anything:
I thought returning the setCookie promise and getCookie promise might make a difference but it does not seem like that is the case.
By default, Cypress clears up all cookies before every test is run. They have an api to keep a cookie for the next test execution which is Cypress.Cookies.preserveOnce
Back to your use case, you can call Cypress.Cookies.preserveOnce('XSRF-TOKEN') in the suite-level beforeEach in every suite where you want to get the token. If you don't want to repeat the call, you can move it inside your getCSRFToken command.
Cypress.Commands.add("getCSRFToken", () => {
Cypress.Cookies.preserveOnce('XSRF-TOKEN')
cy.getCookie('XSRF-TOKEN').then((cookie) => {
.....
});
});

Trouble understanding axios error handling in react

I am learning about react and django. I have installed django-rest-auth to handle account creations and authentication for users. I also wanted to learn about react and I have install axios to make http request to my django rest api. I want to have a "splash" page where users would first access the site. If the user is already logged in they'll see their profile and other content. If the user isn't logged in they should be presented a login page.
Here's my App.js code I have so far.
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import logo from './logo.svg';
import './App.css';
function LoginPage(props) {
console.log('LoginPage props are:');
console.log({ props });
return (<div className="LoginPage">props are: {props}</div>)
}
function SplashPage(props) {
const [currentUser, setCurrentUser] = useState(null);
console.log('SplashPage props are:');
console.log({ props });
const userUrl = 'http://localhost:8000/rest-auth/user/';
console.log('userUrl is:' + userUrl);
axios.get(userUrl)
.then(res => { setCurrentUser(res.data); })
.catch((error) => {
console.log(error.response);
return (<div><LoginPage /></div>);
})
return (<div className="SplashPage">[{userUrl}] [{currentUser}] </div>);
}
function App() {
return (
<div>
<SplashPage />
</div>
);
}
export default App;
Heres my index.js file:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers:
serviceWorker.unregister();
When I go to http://localhost:3000 I get this result:
In the developer console looks like
I had hoped to see the content of my LoginPage function.
[UPDATED ANSWER]
You are returning <div className="SplashPage">[{userUrl}] [{currentUser}] </div> before <div><LoginPage /></div> because it is outside the axios .then() chain ( ie it called directly after the axios.get() and before any code in the .then() or the .catch() blocks )
Should work:
initialize a current user with a loaderState to avoid content flicker
Update state within the axios .then() or .catch()
Use state to determine what to return from function outside of the promises
-
function SplashPage(props) {
const [currentUser={notLoaded:true}, setCurrentUser] = useState(null);
const userUrl = 'http://localhost:8000/rest-auth/user/';
axios.get(userUrl).then(res => {
setCurrentUser(res.data);
}).catch((error) => {
console.log(error)
setCurrentUser(null)
})
//user no authorized
if(!currentUser)
return <LoginPage />
//user authorization unknown
if(currentUser.notLoaded)
return <div/>
//we have a user!
return <div className="SplashPage">{userUrl} {currentUser}</div>
}
[ORIGINAL ANSWER]
EDIT: sorry I misunderstood your question but will leave my original answer here in case someone comes looking for a related issue.
You are getting a 403 error with the message:
Authentication credentials not provided
You need to add some sort of authorization to your request (consult your django-rest-auth configuration/documentation for how it expects authorization from incoming requests).
You can either set this up for every api call manually or set this up via axios.interceptors.request.use() which you will need to import and call somewhere in your application (such as in your app.js or index.js)
The following example:
uses axios.interceptors
adds an authorization token to the Authorization header
utilizes the standard 'bearer TOKEN'
uses firebase auth to demonstrate retrieving token via async
(your actual implementation will depend on how your api is set up and your authorization flow)
addAuthHeader.js:
import axios from 'axios';
import * as firebase from 'firebase/app';
const apiUrl = 'http://localhost:8000/' // '/' if using the preferred http-proxy-middleware
export default addAuthHeader = () =>
//if firebase auth callback should be asyncasync
axios.interceptors.request.use(async (config) => {
if(config.url.startsWith(apiUrl)){
const token = await firebase.auth().currentUser.getIdToken(true)
config.headers.Authorization = `bearer ${token}`;
return config;
}
});
App.js:
addAuthHeader()

What is wrong with my timestamp in my MWS request?

If I submit a request to MWS via the scratchpad(AmazonServices/Scratchpad),
it is successful, and I am able to view the details of the successful request. In particular, the timestamp on the request looks like this:
&Timestamp=2018-08-14T18%3A30%3A02Z
If I literally take this timestamp, as is, and try to use it in my code to make the same exact request, I get an error:
<Message>Timestamp 2018-08-14T18%3A30%3A02Z must be in ISO8601
format</Message>\n
Here is the function I am trying to place it in: (some chars changed in sensitive params)
exports.sendRequest = () => {
return agent
.post('https://mws.amazonservices.com/Products/2011-10-01')
.query({
AWSAccessKeyId: encodeURIComponent('BINAJO5TPTZ5TTRLNGQA'),
Action: encodeURIComponent('GetMatchingProductForId'),
SellerId: encodeURIComponent('H1N1R958BK8TTH'),
SignatureVersion: encodeURIComponent('2'),
Timestamp: '2018-08-14T18%3A30%3A02Z',
Version: encodeURIComponent('2011-10-01'),
Signature: encodeURIComponent(exports.generateSignature()),
SignatureMethod: encodeURIComponent('HmacSHA256'),
MarketplaceId: encodeURIComponent('ATVPDKIKX0DER'),
IdType: encodeURIComponent('UPC'),
'IdList.Id.1': encodeURIComponent('043171884536')
})
.then(res => {
console.log('here is the response');
console.log(res)
})
.catch(error => {
console.log('here is the error');
console.log(error);
})
}
What is even more strange, is that this is the path the request is being sent to:
path: '/Products/2011-10-01?
AWSAccessKeyId=BINAJO5ZPTZ5YTTPNGQA&Action=GetMatchingProductForId&SellerId=H1N1R958ET8THH&SignatureVersion=2&Timestamp=2018-08-14T18%253A30%253A02Z&Version=2011-10-01&Signature=LwZn5of9NwCAgOOB0jHAbYMeQT31M6y93QhuX0d%252BCK8%253D&SignatureMethod=HmacSHA256&MarketplaceId=ATVPDKIKX0DER&IdType=UPC&IdList.Id.1=043171884536' },
The timestamp is not the same as the one I placed in the query. Why is this happening?
Your HTTP library is already doing the url-encoding for you, so you're double-encoding things. Remove all references to encodeURIComponent() and format your timestamp normally, with : and not %3A. Observe what happens to the generated URL.
Why? URL-encoding isn't safe to do repeatedly.
: becomes %3A with one pass, but it becomes %253A with a second pass, which is wrong.

ReactJS Component testing with mocked http calls

I've taken a ReactJS component (rendering the latest gist URL for a given user) from the React docs, and was wondering what is the best way to unit test such a component :
The goals are
Test in isolation (using mocked http calls)
Use our existing test setup (mocha)
Keep things simple
Verify that eventually, when the http call in the component success, the state change triggered a re-render, and an anchor element is rendered the proper url in it.
Here's the component I want to test:
import React from 'react'
import $ from 'jquery'
export default React.createClass({
getInitialState: function() {
return {
username: '',
lastGistUrl: ''
};
},
componentDidMount: function() {
fetch(this.props.source).then(function(response) {
return response.json()
}).then(function(json) {
this.setState({
username: json[0].owner.login,
lastGistUrl: json[0].html_url
});
}.bind(this)).catch(function(ex) {
console.log('parsing failed', ex)
})
},
render: function() {
return (
<div>
{this.state.username}'s last gist is
<a href={ this.state.lastGistUrl}>here</a>.
</div>
);
}
});
And here is my first attempt at testing it:
import TestUtils from 'react-addons-test-utils'
import React from 'react'
import { expect } from 'chai'
import { findDOMNode } from 'react-dom'
import UserGist from '../assets/js/components/UserGistWithFetch'
import nock from 'nock'
describe('UserGistWithFetch', () => {
it('Displays the correct url', (done) => {
nock.disableNetConnect();
nock('https://api.github.com')
.get('/users/octocat/gists')
.reply(200, [{owner:"octocat",html_url:"https://gist.github.com/6cad326836d38bd3a7ae"}])
const gist = TestUtils.renderIntoDocument(<UserGist source="https://api.github.com/users/octocat/gists"/>)
let a = TestUtils.scryRenderedDOMComponentsWithTag(gist, 'a')[0]
expect(a.getAttribute('href')).to.be.equal("https://gist.github.com/6cad326836d38bd3a7ae")
done()
})
})
This test obviously fails, as the component is initially rendered before the mock callback is executed, not rendering the anchor correctly.
The test fails before the mocked http call returns, and the component doesn't get a chance to re-render.
From what I understand, Mocha provides ways to do async testing (using the done() function), but I can't find a hook in my test to put this.
What tools / frameworks would I need to accomplish that ?

How to unit test file upload with Supertest -and- send a token?

How can I test a file upload with a token being sent? I'm getting back "0" instead of a confirmation of upload.
This is a failed test:
var chai = require('chai');
var expect = chai.expect;
var config = require("../config"); // contains call to supertest and token info
describe('Upload Endpoint', function (){
it('Attach photos - should return 200 response & accepted text', function (done){
this.timeout(15000);
setTimeout(done, 15000);
config.api.post('/customer/upload')
.set('Accept', 'application.json')
.send({"token": config.token})
.field('vehicle_vin', "randomVIN")
.attach('file', '/Users/moi/Desktop/unit_test_extravaganza/hardwork.jpg')
.end(function(err, res) {
expect(res.body.ok).to.equal(true);
expect(res.body.result[0].web_link).to.exist;
done();
});
});
});
This is a Working test:
describe('Upload Endpoint - FL token ', function (){
this.timeout(15000);
it('Press Send w/out attaching photos returns error message', function (done){
config.api.post('/customer/upload')
.set('Accept', 'application.json')
.send({"token": config.token })
.expect(200)
.end(function(err, res) {
expect(res.body.ok).to.equal(false);
done();
});
});
Any suggestions are appreciated!
With supertest 4.0.2 I was able to set the token and attach the file:
import * as request from 'supertest';
return request(server)
.post('/route')
.set('Authorization', 'bearer ' + token)
.attach('name', 'file/path/name.txt');
And even better, per the docs, you can make a Buffer object to attach:
const buffer = Buffer.from('some data');
return request(server)
.post('/route')
.set('Authorization', 'bearer ' + token)
.attach('name', buffer, 'custom_file_name.txt');
It seems like the token field is overrided when attaching a file. My workaround is to add token to URL query parameter:
describe('Upload Endpoint - FL token ', function (){
this.timeout(15000);
it('Press Send w/out attaching photos returns error message', function (done){
config.api.post('/customer/upload/?token='+config.token)
.attach('file', '/Users/moi/Desktop/unit_test_extravaganza/hardwork.jpg')
.expect(200)
.end(function(err, res) {
expect(res.body.ok).to.equal(false);
done();
});
});
Your authentication middleware must be set to extract the JWT from URL query parameter. Passport-JWT performs this extraction on my server.
The official document states
When you use .field() or .attach() you can't use .send() and you must not set Content-Type (the correct type will be set for you).
So replace
.send({"token": config.token})
with
.field("token", config.token)