I am using React with axios to the frontend and once I am sending the post request I get the folowing error "Unhandled rejection SequelizeUniqueConstraintError: Validation error", but at the frontend it is not getting any problem.
How could I handling this at the frontend to show the message for the user?
<Button
type='submit'
variant='contained'
color='primary'
size='large'
onClick={() => {
axios
.post(
`http://${config.host}:${config.port}/apartment`,
{
apartment_id: apartment_id,
apartment_block_id: selected_tower,
apartment_block_name:
apartment_data.apartment_block_name,
apartment_floor: apartment_floor,
apartment_size: selected_apartment_data,
apartment_parking_id: selected_apartment_data,
},
)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}}
>
Cadastrar
</Button>
Related
this is my login post method in the reactjs frontend
const login = () => {
Axios.post("http://localhost:3001/api/users/login", {
email: values.email,
password: values.password,
}).then((response) => {
console.log(response.data);
}).catch(err =>{
console.log(err)
})
};
this is my expressjs server side, here i have login post method for reactjs frontend, where iam on response i want to send token to set in cookie whenever user post on login method, below is code for login post method
login: (req, res) => {
const body = req.body;
console.log("req.body :", req.body);
getUserByEmail(body.email, (err, results) => {
console.log("results :", results);
if (err) {
console.log(err);
return;
}
if (!results) {
res.json({
status: "failure",
msg: "Invalid email or password",
});
}
const result = compareSync(body.password, results.password);
const SECRET_KEY = "xyz123";
if (result) {
results.password = undefined;
const jsontoken = sign({ result: results }, SECRET_KEY, {
expiresIn: "1h",
});
// console.log(res)
res.cookie("token", jsontoken, {
httpOnly: true,
domain: "http://localhost:3000/login",
});
return res.json({
status: "Success",
msg: "login Successfully",
token: jsontoken,
});
} else {
return res.json({
status: "failure",
msg: "Invalid email or password",
});
}
});
},
What you could do, that is actually more secure, is tell the browser using headers on the response to create a cookie.
There is a header in HTTP called Set-Cookie, which is responsible to do just that, you can read more about it here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie.
The way you add it to your request on express is by calling the res.cookie function on your express request handler. I would suggest telling the cookie to be httpOnly in order for it to not be accessible through JS code, this is just a way to avoid XSS attacks.
Here you have an example to how to achieve that:
res.cookie('token', jsontoken, { httpOnly: true });
Then in order to access the cookie, you would need to use the cookieParser middleware which is responsible in putting all the cookies the client sent in req.cookies.
You use it this way:
app.use(express.cookieParser());
I am trying to achieve real-time data from twilio server-less function. I am using a boilerplate function edited a little bit.What I want is json data in server and voice response in call consecutively .but the following code is not sending json data to server.
const axios = require('axios');
exports.handler = function (context, event, callback) {
let twiml = new Twilio.twiml.VoiceResponse();
twiml.say('you are welcome ');
const instance = axios.create({
baseURL: 'http://fafc4eac4162.ngrok.io/',
timeout: 3000,
});
instance
.post('/test', {
id: 1,
title: 'Twilio'
})
.then((response) => {
console.log(JSON.stringify(response.data));
})
.catch((error) => {
console.log(error);
return callback(error);
});
return callback(null, twiml);
};
It shows below error,but it sends data successfully if I do not use the voice response callback return callback(null, twiml) and rather use simple return callback(null, response.data);
{"message":"timeout of 3000ms exceeded","name":"Error","stack":"Error: timeout of 3000ms
exceeded\n at createError (/var/task/node_modules/axios/lib/core/createError.js:16:15)\n
at RedirectableRequest.handleRequestTimeout
(/var/task/node_modules/axios/lib/adapters/http.js:280:16)\n at Object.onceWrapper
(events.js:286:20)\n at RedirectableRequest.emit (events.js:198:13)\n at
Timeout._onTimeout (/var/task/node_modules/follow-redirects/index.js:166:13)\n at
ontimeout (timers.j...
The return callback(null, twiml); should be in the .then block.
.then((response) => {
console.log(JSON.stringify(response.data));
return callback(null, twiml);
})
Also, the error indicates the 3000ms timeout is hit, is your application returning a 200-OK?
I have a nuxt app with express and mySQL.
Problem : I am unable to display the express res.send() custom error message on the vue side
Let's pretend I want to display infos of one single user.
Here is my back-end code :
// Find a single User with a userId
exports.findOne = (req, res) => {
User.findById(req.params.userId, (err, data) => {
if (err) {
if (err.kind === 'not_found') {
res.status(404).send({
message: `Not found User with id ${req.params.userId}.`
})
} else {
res.status(500).send({
message: 'Error retrieving User with id ' + req.params.userId
})
}
} else { res.send(data) }
})
}
And here is the Vue part
<script>
import axios from 'axios'
import appNavbar from '~/components/appNavbar.vue'
export default {
components: {
appNavbar
},
data () {
return {
userId: '',
userData: '',
errorMsg: ''
}
},
methods: {
fetchUser (evt) {
evt.preventDefault()
return axios.get('/api/users/' + this.userId)
.then((res) => {
this.userData = res.data
})
.catch((err) => {
this.errorMsg = err.toJSON()
})
}
}
}
</script>
When I give the id of a non-existing user, I want to be able to get the custom error message written in the back, and display it in the front
BUT I only get this JSON
{ "message": "Request failed with status code 404", "name": "Error" }
Does anyone have a clue ?
Thanks !
This error maybe occours because you are not setting the host when you call teh API at line:
return axios.get('/api/users/' + this.userId)
404 error is because browser not found this endpoint.
In this case, I recommend you try to call this endpoint in another tool (like Postman) and certify if your API is responding correctly.
After that, fix your call to endpoint, maybe it will be somwthing like the code bellow and try again:
return axios.get(`${your host here}/api/users/ + ${this.userId}`)
EDIT : SOLUTION FOUND
Answer found here: https://github.com/axios/axios/issues/960#issuecomment-309287911
On the vue part, the catch should return err.response, and not just err.
So in order to display your custom error message, it should be like this:
.catch((err) => {
this.errorMsg = err.response
This question already has answers here:
JSON Parse error: Unrecognized token'<' - react-native
(16 answers)
Closed 2 years ago.
I'm learning react native. here I am making a login logout API to use clien.
when i try in postman, the result is right and right but when I use the API,
I get a problem which is:
JSON Parse error: Unrecognized token '<'
this my code
class AuthScene extends Component {
constructor(props) {
super(props);
this.state = {
username : '',
password : ''
}
}
login= ()=>{
const {username,password} = this.state;
// alert(username);
fetch('https://example.com/auth', {
method: 'POST',
headers: {
'Accept' : 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: username,
password: password
})
})
.then((response) => response.json()).then((responseJson) => {
alert(JSON.stringify(responseJson));
console.log(JSON.stringify(responseJson, null, 4))
}).catch((error) => {
alert(JSON.stringify(error));
console.log(error);
// done();
});
}
and
render() {
return (
<Form style={styles.mainForm}>
<Item style={styles.formItems}>
<Input placeholder="Username" style={styles.Input} onChangeText={username => this.setState({username})}/>
</Item>
<Item style={styles.formItems}>
<Input style={styles.Input} secureTextEntry={true} onChangeText={(password) => this.setState({password})}/>
</Item>
<View style={styles.Button}>
<Button block info style={styles.mainBtn} onPress={this.login}>
<Text style={styles.btnText}>Submit</Text>
</Button>
</View>
</Form>
);
}
how to deal with those things?
Is there a problem with my json or my code isn't correct?
Please check your headers in code is matching with the postman or not..
i'm getting the 'unauthorized' error when trying to post a new comment with axios ..... i added (console.log(this.user.api_token);) just before axios.post in postComment() method . the output is : "undefined" !!!!!!!!!!
i'm learning and i don't know much about api's . but i don't think user api_token is to be set up manually .or does it ???
the script :
<script>
const app = new Vue({
el: '#app',
data: {
comments: {},
commentBox: '',
post: {!! $post->toJson() !!},
user: {!! Auth::check() ? Auth::user()->toJson() : 'null' !!}
},
mounted() {
this.getComments();
},
methods: {
getComments() {
axios.get('/api/post/'+this.post.id)
.then((response) => {
this.comments = response.data
})
.catch(function (error) {
console.log(error);
});
},
postComment() {
console.log(this.user.api_token);
axios.post('/api/post/'+this.post.id , {
api_token: this.user.api_token,
body: this.commentBox
})
.then((response) => {
this.comments.unshift(response.data);
this.commentBox = '';
})
.catch((error) => {
console.log(error);
})
}
}
})
api route
Route::get('/post/{post}', 'CommentController#index');
Route::middleware('auth:api')->group(function () {
Route::post('/post/{post}', 'CommentController#store');
});
CommentController
public function index(Post $post){
return response()->json($post->comments()->with('user')->get());
}
public function store(Request $req,Post $post){
$comment=$post->comment()->create([
'user_id'=>auth::id(),
'body'=>$req->body
]);
$comment=Comment::where('id',$comment->id)->with('user')->first();
return $comment->toJson;
}
If you are trying to consume your own api from vuejs there's no need to set the api token manually. Just update the web middleware group in app/Http/Kernel.php to include this line:
\Laravel\Passport\Http\Middleware\CreateFreshApiToken::class
This middleware will attach a laravel_token cookie that contains an encrypted JWT that Passport will use to authenticate API requests from your JavaScript application.
Read more here: https://laravel.com/docs/5.6/passport#personal-access-tokens
But, if you are consuming this same api from an external source like a mobile app, an api token will be required by passport to authenticate the request. The token can be created when the user is logged in or registered. Here's how:
//create a token
$token = $user->createToken('Token Name')->accessToken;
Then add an headers object to axios when making a request to the api
axios({
method: 'method',
url: 'url',
headers: {
'Accept' => 'application/json',
'Authorization' => 'Bearer '.$token
}
})
.then()
.catch()
Read more here: https://laravel.com/docs/5.6/passport#managing-personal-access-tokens