i can't send the firebase token to the backend, i thought the problem was that the function was not asynchronous but it still didn't work for me, please i need help, thanks!
user.getIdToken(true)
.then(function(idToken) {
const path = 'http://localhost:8000/api/google-login'
console.log(idToken)
axios.post(path , idToken)
.then((response) => {
console.log('anda o no anda')
})
.catch((error) => {
console.log(error);
});
}).catch(function(error) {
console.log(error)
});
the error in console.
POST http: // localhost: 8000 / api / google-login 500 (Internal Server Error)
but if I copy the idtoken and send it manually to the backend it works.
you can do it now, you were sending the token without your key
'''
axios.post(path , {'token_id':idToken})
'''
Related
I've been stuck with this problem for 3 days. I'm using React.js on the frontend with axios and want to upload the file to the server. There is an API endpoint which is a post endpoint something like this.
POST- https://88.66.123.122:20000/b1s/v1/Attachments2
This endpoint basically uploads the files to the server file system with the successful response that has 201 status. The response is successfully fine when I test the endpoint with the Desktop client Postman and the code snippet generated by this tool is this.
But I want to achieve this thing in browser UI. So I'm using React.js for this.
This endpoint also needs an authorization cookie in the request header to make sure the user is authenticated. So In the UI, I created a login button that basically sends a post request with a hardcoded credentials to the login endpoint and giving me a successful response with a session id.
I'm saving the session id in the browser as a cookie for the upload file but when I'm sending the cookie with the request, I'm getting the following response in the browser
Refused to set unsafe header "Cookie"
and the response I'm getting back with the following JSON.
POST https://88.66.123.122:20000/b1s/v1/Attachments2 [401 (Unauthorized)]
{
"error" : {
"code" : 301,
"message" : {
"lang" : "en-us",
"value" : "Invalid session."
}
}
}
I don't know How I can solve this problem? You can see the GIF.
Code:
import React from 'react';
import axios from 'axios';
const URL_LOGIN = `${process.env.REACT_APP_SERVER}Login`;
const COMPANY_DB = process.env.REACT_APP_DB;
const URL_ATTACHMENT = `${process.env.REACT_APP_SERVER}Attachments2`;
const CREDENTIALS = {
UserName: process.env.REACT_APP_USERNAME,
Password: process.env.REACT_APP_PASSWORD,
CompanyDB: COMPANY_DB
};
function App() {
const [isLogin, setIsLogin] = React.useState(false);
const [selected, setSelected] = React.useState(null);
function onClick() {
setIsLogin(true);
axios
.post(URL_LOGIN, CREDENTIALS)
.then(function (response) {
setIsLogin(false);
console.log(response.data);
})
.catch(function (err) {
setIsLogin(false);
console.log(err);
});
}
// onUpload
function handleUpload(event) {
console.log('File set', event.target.files[0]);
setSelected(event.target.files[0]);
}
function uploadSubmit() {
const formData = new FormData();
formData.append('files', selected, selected?.name);
axios
.post(URL_ATTACHMENT, formData)
.then(function (response) {
console.log('response', response);
})
.catch(function (err) {
console.log('err', err);
});
}
return (
<div>
<div>
<button type="button" onClick={onClick} disabled={isLogin}>
Login Create Cookie
</button>
</div>
<hr />
<div>
<div>
<input type="file" onChange={handleUpload} />
</div>
<button type="button" onClick={uploadSubmit}>
Upload File
</button>
</div>
</div>
);
}
export default App;
The cookies are managed by the server, not the client. In your case, you are using a cookie with HttpOnly flag. The client side scripting will not allow you to read the value of Cookies as it is a security threat.
In your nodejs application, the server must be sending a Cookie in response. The server must be doing something like this:
// nodejs (express)
res.cookie('cookieKey', "value", { maxAge: 900000, httpOnly: true });
notice the httpOnly flag, this flag prevents the cookie to be used by the client-side scripting.
Once you set the cookie in response to your NodeJs (Express) request, your browser should automatically start sending the Cookie with each of your requests.
If the request is cross-origin be sure to add withCredentials: true as a header in the axios request
After successfully getting the cookie/token from the server, pass the token in the header. (depends on how you are securing your API endpoint.)
axios
.post(URL_ATTACHMENT, formData, { headers : { header : token }})
.then(function (response) {
console.log('response', response);
})
.catch(function (err) {
console.log('err', err);
});
I'm using the open weather API to make a get request based on a zipcode passed in as a query parameter. When I run the endpoint in Postman I receive a successful response and can see the data. When I run the request from my app (even with a hard coded value for testing) I get a 404 not found.
Endpoint from my server file:
const weatherCtlr = require('./controllers/weatherController);
app.get('/api/weather', weatherCtlr.getWeather);
My Controller
const axios = require('axios');
const {APIKEY} = process.env;
module.exports ={
getWeather :(req, res)=>{
const {zipcode} = req.body;
axios.get(`https://api.openweathermap.org/data/2.5/weather?zip=${zipcode}&APPID=${APIKEY}`)
.then(()=>{
res.sendStatus(200);
})
.catch(err=>console.log(err))
}
}
Client Side, (axios is imported)
getWeather =()=>{
const {zipcode} = this.state.canyon;
axios.get('/api/weather', {zipcode})
.then(res=> this.setState({weather: res.data)})
.catch(err=>console.log(err))
}
I call the method on an on click
onClick={()=>this.getWeather()}
I'm not really sure what the issue is. I know the api key is good because I when I test my actual endpoint localhost.../api/weather and send a zipcode in the body it works.
What stands out is that you send a body to your server using get:
getWeather =()=>{
const {zipcode} = this.state.canyon;
axios.get('/api/weather', {zipcode})
.then(res=> this.setState({weather: res.data)})
.catch(err=>console.log(err))
}
The GET method does not accept a body. Then on the server side you parse it out like this:
const {zipcode} = req.body;
I would be very surprised if you actually get that zipcode. Most likely that will be undefined.
So I would try changing your client side request to:
axios.post('/api/weather', {zipcode})
Once you get the response back from the API, you can send it back to your app like so:
axios.get(`https://api.openweathermap.org/data/2.5/weather?zip=${zipcode}&APPID=${APIKEY}`)
.then((response) => {
res.json(response.data);
})
.catch(err => {
console.log(err);
res.json({msg: 'Error'})
})
I'm trying to send requests to the discord web API but keep getting a 401 response code. Almost all of the answers I can find online are from people who were using a bearer token instead of the bot token, and changing to the bot token worked. I'm using the bot token and still getting a 401. However, I know that this bot token is valid because trying to launch node bot.js with an invalid token throws an error and doesn't launch the bot. My code right now is simply
const Discord = require('discord.js');
const client = new Discord.Client();
const auth = require('./auth.json');
const axios = require('axios');
const headers = {
'Authorization': `Bot ${auth.token}`
};
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on('message', msg => {
/* If the author is a bot, do nothing */
if (msg.author.bot) {
return;
}
/* Only perform an action if the first character is ? */
if (msg.content.substring(0, 1) == '?' && msg.content.length > 1) {
var message = msg.content.substring(1).toLowerCase();
//console.log(message);
//console.log(msg);
//console.log(msg.channel.name);
switch (message) {
case 'gos':
axios.get(`https://discordapp.com/api/channels/${msg.channel.id}/messages`, headers)
.then(response => {
console.log(response);
}).catch(err => {
console.log(err);
});
break;
case 'dolphin':
msg.reply('dolphin', {files: [
"https://www.dolphinproject.com/wp-content/uploads/2019/07/Maya-870x580.jpg"
]});
break;
}
}
});
client.login(auth.token);
I've tried doing the request in postman with hardcoded values and I get the same response, so I do not think it is a syntactical error, but I cannot be sure. Thanks in advance for any help.
As I understood from your question, you are getting the same response from postman (401 Unauthorized), so the only reason for that is that the access token is not valid or you do not have permission to do such call to the API or channel from discord.
Another thing you should see is the way you are sending your headers in axios, here I can share with you the correct way to send headers:
How to set header and options in axios?
Also check that "auth.json" has the token correctly as your are calling it (auth.token).
i came up with this problem with ReactJS and ExpressJS: So basically user uploads some info on /info route with React & axios. then user gets route params from server side to redirect to:
axios.post('/info', SomeData)
.then(res => res.data)
.then(data =>{
window.location.replace(`/info/${data.id}`)
})
this is piece of cake but when user redirects to that page problem occurs, i need to get data from that page. i can get route params and perform request on client side like this:
componentDidMount(){
const { match: { params } } = this.props;
axios.get(`/api/info/${params.id}`)
}
but how can i get request on server side? how can express access that "id" to search it in database and query data with it to send back to client? like:
app.get('/api/info/:id', async (req,res)=>{
await db.find({id: req.params.id}, (data) =>{
res.status(200).send({data})
})
})
Any help? Thanks!
From the component itself same as the GET use your param and call your service same thing to POST
postUserInfo = () => {
const userInfo ={};
axios.post(`/api/info/${params.id}`,userInfo).then(()=>{
console.log("user info posted");
})
}
Example:
<Form onSubmit={this.postUserInfo}> </form>
I am sending an axios request to an express url "getstatus" - on my local development everything is fine, but once the files are on a server there is still my localhost in the url path.
this.$axios.get('api/getstatus', {
}).then(function (response) {
})
.catch(function (error) {
});
app.get('/getstatus', async (req, res) => {
// stuff happening
})
-> ok on localhost
-> error on sever: Request URL: http://localhost:3000/api/getstatus
Why is my local development url still getting used? it should be http://myserver.com/api/getstatus
It seems like the axios get request should be /api/getstatus not api/getstatus
Another thing is you should set an API_URL variable in your dot env file and on development set it to localhost and on your server set it to your server URL.
something like this
this.$axios.get(`${process.env.API_URL}/api/getstatus`, {
}).then(function (response) {
// Code here
})
catch(function (error) {
// Error code here
});
Can you try below code change to use the full url in the get request. If it works you can parameterize the myserver.com
this.$axios.get('http://myserver.com/api/getstatus', {
}).then(function (response) {
})
.catch(function (error) {
});