I have an issue with sign up.
When I try to sign up, server responses with 401 Unauthorized
This problem happens only when I start this project on localhost using docker. If I git clone project on my localhost - it works, but when I use docker - it doesn't
Request:
POST /auth/signup HTTP/1.1
Authorization: Bearer null
Response:
HTTP/1.1 401 Unauthorized
There is code below:
//authApi.js
import {$api_id} from '../api'
export const AuthApi = {
async signup(payload) {
const response = await $api_id.post('/auth/signup', payload)
return response
},
async signin(payload) {
const response = await $api_id.post('/auth/signin', payload)
return response
}
}
//storage.js
const storage = {
get: (key) => {return localStorage.getItem(key)}
}
export const getAccessToken = () => {
return storage.get('accessToken')
}
//api.js
import axios, {AxiosResponse} from 'axios'
import {getAccessToken, getDeviceId} from 'utils'
export const API_URL = process.env.NEXT_PUBLIC_API_KEY
$api_id.baseURL = process.env.NEXT_PUBLIC_API_KEY
export const $api_id = axios.create({
withCredentials: false,
baseURL: API_ID_URL,
})
$api_id.interceptors.request.use((config) => {
config.headers.Authorization = `Bearer ${getAccessToken()}` //getAccessToken(storage.get('accessToken'))
if(config.data.avatar) {
const formData = new FormData()
formData.append('deviceId', getDeviceId()) //getDeviceId(storage.get("deviceId")) - fingerprintjs
Object.entries(config.data).forEach(([name, value]) => {
formData.append(name, value)
})
config.data = formData
} else {
let data
if(typeof config.data === 'string') {
data = JSON.parse(config.data)
} else {
data = config.data
}
if(!data.deviceId) {
data.deviceId = getDeviceId()
}
// console.log({data})
}
return config
})
Thank you!
Related
In my code, when I try to call an external endpoint from the Jira issue panel app, I get a log "try" and the fetch doesn't happen.
I would appreciate it, if someone could help me.
Thanks in advance!
import ForgeUI, {
IssuePanel,
useProductContext,
useEffect,
} from "#forge/ui";
import { url } from "./constants";
import API, { fetch } from "#forge/api";
const Panel = () => {
const productContext = useProductContext();
const fetchTaskItems = async (issueID) => {
const requestOptions = {
method: "GET",
mode: "cors",
headers: { "Content-Type": "application/json" },
};
try {
console.log("try");
const res = await fetch(
url + `experience/task/item/${issueID}`,
requestOptions
);
console.log(res);
} catch (err) {
console.log(err.message);
}
};
useEffect(() => {
const currentIssueId = productContext.platformContext.issueKey;
console.log("Current issue ID:", currentIssueId);
fetchTaskItems(currentIssueId);
}, []);
You can import userAction from ForgeUI
import ForgeUI, {useAction} from "#forge/ui";
Then call your fetchTaskItems like this
const [req] = useAction(
(value) => value,
async () => await fetchTaskItems()
);
let me know if it works,
I've got a problem with sign up request on my local machine. When I set a project on my local machine from docker and tried to sign up to mt local server(localhost:3000), I got an error 401 Unauthorized, but I don't get this error when I git clone project fron github and run npm run dev. And it works fine when the project on my web server in internet.
Tokens should be saved in local storage, but there are no tokens at all.
I tried to set {withCredentials: true} but it didn't work too.
//storage.js
const storage = {
get: (key) => {return localStorage.getItem(key)}
}
export const getAccessToken = () => {
return storage.get('accessToken')
}
//authApi.js
import {$api_id} from '../api'
export const AuthApi = {
async signup(payload) {
const response = await $api_id.post('/auth/signup', payload)
return response
},
async signin(payload) {
const response = await $api_id.post('/auth/signin', payload)
return response
}
}
//api.js
import axios, {AxiosResponse} from 'axios'
import {getAccessToken, getDeviceId} from 'utils'
export const API_URL = process.env.NEXT_PUBLIC_API_KEY
$api_id.baseURL = process.env.NEXT_PUBLIC_API_KEY
export const $api_id = axios.create({
withCredentials: false,
baseURL: API_ID_URL,
})
$api_id.interceptors.request.use((config) => {
config.headers.Authorization = `Bearer ${getAccessToken()}` //getAccessToken(storage.get('accessToken'))
if(config.data.avatar) {
const formData = new FormData()
formData.append('deviceId', getDeviceId()) //getDeviceId(storage.get("deviceId")) - fingerprintjs
Object.entries(config.data).forEach(([name, value]) => {
formData.append(name, value)
})
config.data = formData
} else {
let data
if(typeof config.data === 'string') {
data = JSON.parse(config.data)
} else {
data = config.data
}
if(!data.deviceId) {
data.deviceId = getDeviceId()
}
// console.log({data})
}
Thanks!
here is my question how to call api recursively untill nested data stack keys are finished
here is my full explaination in image
i found this relatable code for recursion api call at this post recursive api call
function callFW() {
d3.json(url, async function(data) {
Tree["uid"] = data.request.uid
Tree["hid"] = data.firmware.meta_data.hid
Tree["size"] = data.firmware.meta_data.size
Tree["children"] = [];
await BuildTree(data.firmware.meta_data.included_files,Tree["children"]);
console.log(Tree)
})
}
async function BuildTree(included_files, fatherNode) {
if (included_files.length > 0) {
let promises = included_files.map( item => {
let url = endpoint + "file_object/" + item + "?summary=true";
return axios.get(url)
});
const results = await Promise.all(promises);
for(let response of results){
var node = {}
node["uid"] = response.data.request.uid
node["hid"] = response.data.file_object.meta_data.hid
node["size"] = response.data.file_object.meta_data.size
node["children"] = []
fatherNode.push(node)
await BuildTree(response.data.file_object.meta_data.included_files, node["children"]);
};
}
};
this is im using custom useRecurseFetch for getting post api result
but i have no idea how to change this code for recursive api call
import React from 'react';
import qs from 'qs';
import axios from 'axios';
const useRecurseFetch = query => {
const [status, setStatus] = React.useState('idle');
const [result, setResult] = React.useState([]);
const [findClass, setFindClass] = React.useState([]);
// console.log(passVariable);
var data;
data = qs.stringify({
query: `http://www.blabla{ ${query}/category}`,
});
// eslint-disable-next-line no-undef
var Grant = process.env.REACT_APP_GRANT;
// eslint-disable-next-line no-undef
var Client = process.env.REACT_APP_CLIENT;
// eslint-disable-next-line no-undef
var Key = process.env.REACT_APP_KEY;
// eslint-disable-next-line no-undef
var Auth = process.env.REACT_APP_AUTH;
// eslint-disable-next-line no-undef
var Query = process.env.REACT_APP_QUERY;
const queryCall = React.useCallback(
async token => {
if (!token) {
return;
} else {
setStatus('Loading');
var config = {
method: 'POST',
url: `${Query}`,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Authorization:
token.data.token_type + ' ' + token.data.access_token,
},
data: data,
};
axios(config)
.then(response => {
setResult(response.data.results.bindings);
let originalResult = response.data.results.bindings
.filter(ek => ek.class !== undefined && ek)
.map(el => el.obj.value);
setFindClass(originalResult);
setStatus('success');
})
.catch(function (error) {
setStatus('error');
});
}
},
[data]
);
React.useEffect(() => {
const authInitiate = () => {
var data = qs.stringify({
grant_type: `${Grant}`,
client_id: `${Client}`,
client_secret: `${Key}`,
});
var config = {
method: 'POST',
url: `${Auth}`,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
data: data,
};
axios(config)
.then(response => {
queryCall(response);
})
.catch(function (error) {
console.log(error);
});
};
authInitiate();
}, [queryCall]);
return [status, result, findClass];
};
export default useRecurseFetch;
please any one can help me out with this code, im unable to figure out whats going in this code
anyhelp is really saved my day and really so appreciatable
here i called useRecurseFetch custom function in app.js
const [loadingStatus, mainData, addDataToPostItemArray] = useRecurseFetch(
`<kk:cat>`
);
please any one can help me out please im stuck with this process of calling api
Pretty new with NodeJS and Express but want to figure out it is possible to add new objects after loading api via client side. So in the first place it should load the api via server-side which contains the existing objects and output on the client side, and when that is loaded I want to add new objects that I post via server side. So the new posted object should be added added to the json.
Client Side
import { useEffect, useState } from 'react';
import axios from 'axios';
export const App = () => {
const [inputValue, setInputValue] = useState("");
const [posts, setPosts] = useState([]);
useEffect(() => {
const headers = { "Content-Type": "application/json" };
try {
const getData = async () => {
const result = await axios.get('http://localhost:5000', headers);
console.log(result.data);
};
getData();
} catch (error) {
console.log(error);
}
}, []);
const postReview = async value => {
const headers = { "Content-Type": "application/json" };
let data = {
name: value
};
try {
const getData = async () => {
const result = await axios.post('http://localhost:5000/songs', data, headers);
console.log(result.data);
};
getData();
} catch (error) {
console.log(error);
}
};
const submitReview = () => {
postReview(inputValue);
};
return (
<div className="App">
<input
placeholder="Place review"
onChange={e => setInputValue(e.target.value)}
/>
<button onClick={() => submitReview()}>Send</button>
</div>
);
};
export default App;
Server Side
const express = require('express');
const cors = require('cors');
const axios = require('axios');
const app = express();
const port = 5000;
app.use(cors({ origin: '*' }));
app.use(express.json());
app.get("/", async (req, res, next) => {
try {
const { data } = await axios.get('https://raw.githubusercontent.com/XiteTV/frontend-coding-exercise/main/data/dataset.json');
res.status(200).send(data.videos);
} catch (ex) {
res.status(500).send(data.videos);
}
});
app.post('/songs', async (req, res) => {
console.log(reviews.length);
});
I didn't understand what you meant, but I think you want to add more objects to the list of posts, if so, use the following:
setPosts([
...posts,
{
//New post object
}
])
You can post directly in their API.
const postReview = async review => {
const headers = {
"content-type": "application/json",
"Access-Control-Allow-Origin": "*"
};
// axios post request to that api
const response = await axios
.post('https://jsonplaceholder.typicode.com/posts',
{review},
{headers});
};
They described this on their site. Further read
Hope you could help me out with the following. I am trying to upload an excel file of ≈3MB from the client side to the API by first converting the file to a DataURL where after I send it as a string. This is working for smaller files, but it somehow seems to be blocking my larger files.
When I upload the file, I get the following error.
POST body missing. Did you forget use body-parser middleware?
I have done my own research and found more people with the same problem, though I could not find a solution.
https://github.com/apollographql/apollo-server/issues/792
This is the code I am using on the server side.
import { ApolloServer, gql } from 'apollo-server-micro'
type Props = {
_id: string
file: string[]
}
const typeDefs = gql`
type Mutation {
uploadFile(file: [String!]!): Boolean!
}
type Query {
readUpload(_id: String!): Boolean!
}
`
const resolvers = {
Mutation: {
async uploadFile(_: any, { file }: Props) {
console.log(file)
return true
}
},
Query: {
async readUpload(_: any, { _id }: Props) {
}
}
}
const apolloServer = new ApolloServer({
typeDefs,
resolvers
})
export const config = {
api: {
bodyParser: false
}
}
// Ensure to put a slash as the first character to prevent errors.
export default apolloServer.createHandler({ path: '/api/uploads' })
This is the code I am using on the client side.
import { useRef } from 'react'
import { uploadFile } from '../graphql/fetchers/uploads'
import { UPLOAD_FILE_QUERY } from '../graphql/queries/uploads'
export default function Upload() {
const inputElement = useRef<HTMLInputElement>(null)
const submitForm = (event: any) => {
event.preventDefault()
const files = inputElement.current?.files
if (files) {
const fileReader = new FileReader()
fileReader.onload = async () => {
try {
const result = fileReader.result as string
try {
console.log(result)
await uploadFile(UPLOAD_FILE_QUERY, { file: result })
} catch(error) {
console.log(error)
}
} catch(error) {
console.log(error)
}
}
fileReader.readAsDataURL(files[0])
}
}
return (
<form>
<input ref={inputElement} type='file'></input>
<button onClick={(event) => submitForm(event)}>Submit</button>
</form>
)
}
export const config = {
api: {
bodyParser: false
}
}
set bodyParser to true
Set bodyParser size limit
export const config = {
api: {
bodyParser: {
sizeLimit: '4mb' // Set desired value here
}
}
}
you try to send file as string in json? I think you should use multipart/form data on client side and parse them with special middleware on server side
On client special link converts request to multipart/formdata
full example https://github.com/jaydenseric/apollo-upload-examples
import { useMemo } from "react"
import { ApolloClient, createHttpLink, InMemoryCache } from "#apollo/client"
import { setContext } from "#apollo/client/link/context"
import { getUserTokenFromLocalStorage } from "../utils/utils"
import { createUploadLink } from "apollo-upload-client"
let apolloClient
const httpLink = createUploadLink({
uri: "/api/graphql",
headers: {
"keep-alive": "true",
},
})
const authLink = setContext((_, { headers }) => {
let token = getUserTokenFromLocalStorage()
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : "",
},
}
})
function createIsomorphLink() {
if (typeof window === "undefined") {
const { SchemaLink } = require("#apollo/client/link/schema")
const { schema } = require("./schema")
return new SchemaLink({ schema })
} else {
return authLink.concat(httpLink)
}
}
function createApolloClient() {
return new ApolloClient({
ssrMode: typeof window === "undefined",
link: createIsomorphLink(),
cache: new InMemoryCache(),
})
}
export function initializeApollo(initialState = null) {
const _apolloClient = apolloClient ?? createApolloClient()
// If your page has Next.js data fetching methods that use Apollo Client, the initial state
// gets hydrated here
if (initialState) {
_apolloClient.cache.restore(initialState)
}
// For SSG and SSR always create a new Apollo Client
if (typeof window === "undefined") return _apolloClient
// Create the Apollo Client once in the client
if (!apolloClient) apolloClient = _apolloClient
return _apolloClient
}
export function useApollo(initialState) {
const store = useMemo(() => initializeApollo(initialState), [initialState])
return store
}