Flutter: Tenant could not be identified by request data with payload - laravel

I am new in flutter development, I am confuse how to pass tenant id using Laravel API, here is my code.
login() async {
try {
var url = Uri.parse('https://api.currinda2.com/v1/auth/login');
var response = await http.post(
url,
body: {
'email': 'testuser#currinda.com',
'password': 'testuser',
'remember': '1',
},
headers: {
'xtenant': 'asn2',
},
);
log(response.body);
} catch (e) {
log(e.toString());
}
}
But given me this error: Tenant could not be identified by request data with payload: in file /var/app/current/vendor/stancl/tenancy/src/Resolvers/RequestDataTenantResolver.php

Related

Posting image from expo and axios to spring boot server returns error

I wanna send an axios request with photo data to my Spring Boot server but it does not work.
Here is the code:
const updateUserProfile = dispatch => async ({categories, phoneNumber, photo}) => {
try {
const id = await SecureStore.getItemAsync('user_id');
const formData = new FormData()
formData.append("file", {
uri: photo,
name: `${id}_photo`,
type: 'image/png'
})
await request.post(
`/photos/${id}`,
formData,
{
headers: {
'Content-Type': `multipart/form-data; boundary=${formData._boundary}`
},
},
)
dispatch({type: 'update_user_profile', payload: response.data})
} catch (e) {
dispatch({type: 'add_error', payload: 'UPDATE_USER_PROFILE_ERROR'})
}
}
The file URI looks like that and I think its correct:
file:///data/user/0/[...]/ImagePicker/e9255306-dca9-486e-a9
05-e4e1c619b766.jpg
And here is the Spring Boot Controller
#PostMapping("/{userId}")
public void saveObject(#RequestParam(value = "file") MultipartFile file, #PathVariable Long userId) {
photoService.uploadFile(file, userId);
}
Spring Boot works great when I send request with photo from postman but when I want to send the request from updateUserProfile method above, I receive this error:
Resolved [org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'file' is not present]
Okay, finally after many hours I fixed the problem. This github issue helped me a lot https://github.com/axios/axios/issues/4412
So I installed form-data package
npm i form-data
and in the updateUserProfile method added this line just before appending data to formData
FormData.prototype[Symbol.toStringTag] = 'FormData';
so the full method looks like that now:
const updateUserProfile = dispatch => async ({categories, phoneNumber, photo}) => {
try {
const id = await SecureStore.getItemAsync('user_id');
const extenstion = photo.substring(photo.lastIndexOf('.') + 1)
const fileName = photo.replace(/^.*[\\\/]/, '')
const formData = new FormData()
FormData.prototype[Symbol.toStringTag] = 'FormData';
formData.append("file", {
uri: photo,
name: fileName,
type: `image/${extenstion}`
})
await request.post(
`/photos/${id}`,
formData,
{
headers: {
'Content-Type': `multipart/form-data; boundary=${formData._boundary}`
},
},
)
dispatch({type: 'update_user_profile', payload: response.data})
} catch (e) {
dispatch({type: 'add_error', payload: 'UPDATE_USER_PROFILE_ERROR'})
}
}

v4 Bot sendActivity no output in Bot [object Promise]

I do not get an output inside my web chat Bot with the line
await turnContext.sendActivity('No output in Bot? '+this.translateText(turnContext.activity.text));
There is no error message and in the log I get the correct JSON from the Microsoft Cognitive Text Translator API service. But in the Bot Framework emulator I get only [object Promise]?
const request = require('request');
const uuidv4 = require('uuid/v4');
const rp = require('request-promise');
class EchoBot {
constructor(conversationState) {
this.conversationState = conversationState;
}
async onTurn(turnContext) {
if (turnContext.activity.type === ActivityTypes.Message) {
// OK
await turnContext.sendActivity(`${ count }: Alex you said "${ turnContext.activity.text }"`);
// not output in Bot?
await turnContext.sendActivity('No output in Bot? '+this.translateText(turnContext.activity.text));
} else {
await turnContext.sendActivity(`[${ turnContext.activity.type } event detected]`);
}
await this.conversationState.saveChanges(turnContext);
}
async translateText(inputText){
let options = {
method: 'POST',
baseUrl: 'https://api.cognitive.microsofttranslator.com/',
url: 'translate',
qs: {
'api-version': '3.0',
'to': 'de'
},
headers: {
'Ocp-Apim-Subscription-Key': subscriptionKey,
'Content-type': 'application/json',
'X-ClientTraceId': uuidv4().toString()
},
body: [{
'text': inputText
}],
json: true,
};
rp(options)
.then(function (repos) {
console.log(JSON.stringify(repos, null, 4));
return JSON.stringify(repos, null, 4);
})
.catch(function (err) {
console.log("error alex");
});
};
}
Since you are using the response-promise package, I would recommend using async/await instead of the then/catch method. The async/await approach falls more inline with the flow of the BotFramework and will allow you to return the resulting promise from your request to your onTurn method. This is how your translateText function should look:
async translateText(inputText){
let options = {
method: 'POST',
baseUrl: 'https://api.cognitive.microsofttranslator.com/',
url: 'translate',
qs: {
'api-version': '3.0',
'to': 'de'
},
headers: {
'Ocp-Apim-Subscription-Key': subscriptionKey,
'Content-type': 'application/json',
'X-ClientTraceId': uuidv4().toString()
},
body: [{
'text': inputText
}],
json: true,
};
const repos = await rp(options);
return repos[0].translations[0].text;
};
Note, since translateText is an asynchronous method and returns a promise you will have to add await before the function call.
await turnContext.sendActivity('No output in Bot? ' + await this.translateText(turnContext.activity.text));
Hope this helps!

Error during upload image to imgur - inavlid URL

i have some troubles with imgur api. I converted image to base64 code and tried upload it to imgur api. Unfortuatelly I'm receiving an error:
"error": "Invalid URL (data:image/png;base64,iVBORw0KGgoAA..."
Here's my function:
uploadImageToImgur: function (file) {
const url = 'https://api.imgur.com/3/image',
reader = new FileReader();
reader.onloadend = async function () {
let { result } = reader;
try {
const request = await fetch(url, {
method: 'POST',
headers: {
"Authorization": 'my client key',
},
body: result
});
const response = await request.json();
console.log(response);
} catch (e) {
throw new Error(e);
}
}
if (file) {
reader.readAsDataURL(file);
}
}
You need to cut this part out.
You are missing some parameters. Also, make sure your headers have the Client-ID key.
const request = await fetch(url, {
method: 'POST',
headers: {
"Authorization": 'Client-ID {yourKey}',
},
form: {
"image": result,
"type": "base64"
}
});

Google recaptcha v3 always returning error

Following the instructions I get a valid token from my front end (can see in dev tools):
window.grecaptcha
.execute(captchaPkey, { action: 'contact' })
.then((token) => {
// this is what I POST to my API
So in my React front end:
send = (event) => {
event.preventDefault()
this.setState({ busy: true })
window.grecaptcha.ready(() => {
window.grecaptcha
.execute(captchaPkey, { action: 'contact' })
.then((token) => {
// successfully get token
const payload = {
token,
name: this.state.name,
to: this.props.to,
email: this.state.email,
message: this.state.message,
}
// now I'm sending the payload to my API
// My API
update(`${api}/contact/`, {
method: 'POST',
body: JSON.stringify(payload)
}, null)
.then(data => {
this.setState({ busy: false, result: 'Email sent' });
})
.catch(error => {
this.setState({ busy: false, error: error.message });
});
})
})
}
my API controller
async function verifyCaptcha(token) {
return await axios.post('https://www.google.com/recaptcha/api/siteverify', {
secret: process.env.CAPTCHA_PKEY,
response: token
})
}
async function contact({ token, to, name, email, message }) {
const result = await verifyCaptcha(token)
if (!result || !result.data || !result.data.success) {
// always get an error here
throw new Error('Invalid captcha')
}
let targetEmail = 'default#emailaddress'
if (to !== 'admin') {
const user = await User.findOne({ username: to }, { email }).exec()
if (!user) {
throw new Error('User does not exist')
}
targetEmail = user.email
}
// rest of send
}
On my API POST endpoint sends to https://www.google.com/recaptcha/api/siteverify with the body of:
{
secret: process.env.CAPTCHA_PKEY,
response: token
}
Yet I always get "missing-input-response", "missing-input-secret" error. Is this because v3 is new? Still bugs?
Realised in the documentation it states "post params" not post body haha.

Data are not inserted in mongodb, it gives could not get any response error in postman

I build the project using the mean stack. I insert record using postman but I get one error, I try to resolve much time but not to find where is a mistake.
Postman error
This is models user.js file.which is shows userSchema details.
Models -> user.js
var mongoose = require('mongoose');
var bcrypt = require('bcryptjs');
var config = require('../config/database');
// User Schema
var UserSchema = mongoose.Schema({
name: {
type: String,
},
email: {
type: String,
required: true
},
username: {
type: String,
required: true
},
password: {
type: String,
required: true
}
});
var User = module.exports = mongoose.model('User', UserSchema);
module.exports.getUserById = function(id, callback){
User.findById(id, callback);
}
module.exports.getUserByUsername = function(username, callback){
var query = {username: username}
User.findOne(query, callback);
}
module.exports.addUser = function(newUser, callback){
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(newUser.password, salt, (err, hash) => {
if(err) throw err;
newUSer.password = hash;
newUser.save(callback);
});
});
}
This is Routes user.js file. here router of register displays, also define add user status results that can be shown if postman value is inserted in mongo then successfully another wise unsuccessfull message.
Routes -> users.js
var express = require('express');
var router = express.Router();
var password = require('passport');
var jwt = require('jsonwebtoken');
var User = require('../models/user');
// Register
router.post('/register', function(req, res, next){
let newUser = new User({
name: req.body.name,
email: req.body.email,
username: req.body.username,
password: req.body.password
});
User.addUser(newUser, (err, user) => {
if(err){
res.json({success: false, msg:'Failed to Register User'});
} else {
res.json({success: true, msg:'User Registered'});
}
});
});
// Authenticate
router.post('/authenticate', function(req, res, next){
res.send('Authenticate');
});
// Profile
router.get('/profile', function(req, res, next){
res.send('Profile');
});
module.exports = router;
You are sending the request wrongly from Postman. You should not use x-www-form-urlencoded. Use the Raw option at send it as a json object, like this:
{
"name": "Mark Melton",
"email": "xyz#gmail.com",
"username": "shuta",
"password": "Sunala123"
}
This is how it will work, because in your routes, you are using req.body...

Resources