Given a back-end in Node-Js that allows users to be created with the following schema:
POST http://localhost:8080/user
Authorization: {{adminToken}}
Content-Type: application/json
{
"userID": "test",
"userName": "test",
"password": "asdf"
}
A corresponding interface is now created in React, which communicates with the BackEnd and enables the creation of users. The function to create a user looks like this in React:
function createaUser(userID, username,password) {
/* const hash= Buffer.from(`${userID}:${password}`).toString('base64') */
console.log(userID)
const hash="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySUQiOiJhZG1pbiIsImlzQWRtaW5pc3RyYXRvciI6dHJ1ZSwidXNlck5hbWUiOiJEZWZhdWx0IEFkbWluaXN0cmF0b3IgQWNjb3VudCIsImV4cGlyZXMiOjE2NDE1NjgyNzgxNDUsImlhdCI6MTY0MTU2Nzk3OH0.mJff9nuqgHXZVQfWbjeWed3JIRAm2N2s0CYpnXoMyv4"
var safe ={'userID':userID, "userName": username, "password":password};
var data = JSON.parse(JSON.stringify(safe));
console.log(data)
const requestOptions = {
method: 'POST',
headers: { 'Authorization': `Basic ${hash}`},
body: {'Content-Type': 'application/json',data}
};
return fetch('https://localhost:443/user/', requestOptions)
.then(handleResponse)
.then(userSession => {
return userSession;
});}
However, only an empty object is created. So username,userID and password are not recognized. Where is the error ?
CodePudding user response:
Just post safe as it is. Don't convert it to json and stringify. It may work. and also add "accept: */*" to your requestOptions.
CodePudding user response:
React is definitely small-step, but the solution looks like this:
function createaUser(userID, username,password) {
const hash="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySUQiOiJhZG1pbiIsImlzQWRtaW5pc3RyYXRvciI6dHJ1ZSwidXNlck5hbWUiOiJEZWZhdWx0IEFkbWluaXN0cmF0b3IgQWNjb3VudCIsImV4cGlyZXMiOjE2NDE1NjgyNzgxNDUsImlhdCI6MTY0MTU2Nzk3OH0.mJff9nuqgHXZVQfWbjeWed3JIRAm2N2s0CYpnXoMyv4"
const requestOptions = {
method: 'POST',
headers: { 'Authorization': `Basic ${hash}`,'Content-Type': 'application/json' },
body: JSON.stringify({ userID: userID, userName: username, password:password })
};
console.log(requestOptions)
return fetch('https://localhost:443/user/', requestOptions)
.then(handleResponse)
.then(userSession => {
return userSession;
});}
