I'm trying to build a file upload with Next.js and Ant Design using React.
On localhost, everything works fine. When I deployed the instance and try to upload a file, I get the following error:
Request URL: https://my-app.my-team.now.sh/url/for/test/
Request Method: POST
Status Code: 405
Remote Address: 34.65.228.161:443
Referrer Policy: no-referrer-when-downgrade
The UI that I use looks like the following:
<Dragger {...fileUploadProps}>{renderImageUploadText()}</Dragger>
where fileUploadProps are:
const fileUploadProps = {
name: 'file',
multiple: false,
showUploadList: false,
accept: 'image/png,image/gif,image/jpeg',
onChange(info) {
const { status } = info.file;
if (status === 'done') {
if (info.file.size > 2000000) {
setUploadSizeError('File size is too large');
} else {
handleFieldValue(API_FORM_FIELDS.PICTURE, info);
}
} else if (status === 'error') {
setUploadSizeError(`${info.file.name} file upload failed.`);
}
},
};
I assume, it has to do with the server side rendering of Next.js? On the other hand, it might not, because by the time I navigated to url/for/test it should render on the client.
How do you implemented file uploads with Ant Design and Next.js?
Got this to work by passing the prop action="https://www.mocky.io/v2/5cc8019d300000980a055e76" to the <Upload/> component.
The ANTD Upload component must make a POST request to upload the file. It either makes that POST request to the current url, which results in the 405, or to the url specified by the action prop. https://www.mocky.io/v2/5cc8019d300000980a055e76 works as this url.
Inspired by Trey's answer (and because I didn't want to send data anywhere outside my domain) I made a no-op api route that simply returns a success, and then pointed Ant Design <Upload>'s action to /api/noop
/* pages/api/noop.tsx */
import { NextApiRequest, NextApiResponse } from 'next'
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
res.status(200).end('noop')
}
/* Wherever I'm using <Upload /> */
<Upload
...otherProps
action={'/api/noop'}
>
Note: this is specific to Next.js, which makes it easy to create API routes.
This works for me.
By default, the ANTD upload component makes a POST request to upload the file. So, to avoid this, add a customRequest props on Upload as below.
customRequest={({ onSuccess }) => setTimeout(() => { onSuccess("ok", null); }, 0) }
Related
I'm new to shopify development, and can't figure out how to call an authenticated API from a shopify theme-extension. Essentially, I'm trying to make a theme extension, where one of the functionalities is that when a checkbox is clicked, an API that counts the number of products is called.
I have a working api that gets the product count, and in web>index.js, I have set-up the end-point:
app.get("/api/products/count", async (_req, res) => {
const countData = await shopify.api.rest.Product.count({
session: res.locals.shopify.session,
});
res.status(200).send(countData);
});
Under web>frontend>hooks, I have the authenticated hooks set-up as shown below. I've tested that if I call the "api/products/count" API from one of the web pages using useAppQuery, it works as expected, and returns the product count.
import { useAuthenticatedFetch } from "./useAuthenticatedFetch";
import { useMemo } from "react";
import { useQuery } from "react-query";
export const useAppQuery = ({ url, fetchInit = {}, reactQueryOptions }) => {
const authenticatedFetch = useAuthenticatedFetch();
const fetch = useMemo(() => {
return async () => {
const response = await authenticatedFetch(url, fetchInit);
return response.json();
};
}, [url, JSON.stringify(fetchInit)]);
return useQuery(url, fetch, {
...reactQueryOptions,
refetchOnWindowFocus: false,
});
};
In my theme extension code, I've added an event listener to the checkbox which calls getProductCount. In getProductCount, I want to call /api/products/count:
import { useAppQuery } from "../../../web/frontend/hooks";
export const getProductCount = (product) => {
const {
data,
refetch: refetchProductCount,
isLoading: isLoadingCount,
isRefetching: isRefetchingCount,
} = useAppQuery({
url: "/api/products/count",
reactQueryOptions: {
onSuccess: () => {
setIsLoading(false);
},
},
});
}
However, when I run locally and click the checkbox, it returns a 404 error trying to find useAppQuery. The request URL is https://cdn.shopify.com/web/frontend/hooks. It seems like the authentication isn't working because that URL looks incorrect.
Am I missing a step that I need to do in order to call an authenticated API from a theme-extension?
I thought the issue was just the import path for useAppQuery but I've tried different paths, and they all return the same 404 issue.
If you want a hot tip here. In your theme App extension, you do not actually need to make an API call to get a product count. In your theme app extension, you can just use Liquid, and dump the product count out to a variable of your choice, and use the count, display the count, do whatever.
{{ shop.product_count }}
Of course, this does not help you if you need other storefront API calls in your theme App extension, but whatever. In my experience, I render the API Access Token I need in my theme app extension, and then making my Storefront API calls is just a fetch().
The only time I would use authenticated fetch, is when I am doing embedded App API calls, but that is a different beast from a theme app extension. In there, you do not get to make authenticated calls as the front-end is verboten for those of course. Instead you'd use App Proxy for security.
TL:DR; Storefront API calls with a token should not fail with a 404 if you call the right endpoint. You can use Storefront API inside a theme app extension. Inside a theme app extension, if you need backend Admin API access, you can use App Proxy calls.
I'm new to next.js and I wanted to know if I could protect a whole API route via middleware. So for example if i wanted to protect /api/users Could I create /api/users/_middleware.ts and handle authentication in the middleware and not have to worry about authentication in the actual api endpoints? If so, how would I go about doing that? The library i'm using right now is #auth0\nextjs-auth0 so I guess it would look something like this? (Also please forgive me if I code this wrong, I am doing this in the stackoverflow editor)
export default authMiddleware(req,res)=>{
const {user,error,isLoading} = whateverTheNameOfTheAuth0HookIs()
if(user)
{
// Allow the request to the api route
}
else
{
// Deny the request with HTTP 401
}
}
Do I have the general idea correct?
next-auth v4 introduced middleware for this purpose. The basic use case is pretty simple.
You can add a middleware.js file with the following:
export { default } from "next-auth/middleware"
export const config = { matcher: ["/dashboard"] }
Other use cases can be found in the documentation
You can use middleware for that, something similar to this example from the documentation.
For a sub-directory inside pages, you can create a _middleware.ts file. It will run for all pages in this directory. It looks something like this:
import { NextRequest, NextResponse } from 'next/server'
export function middleware(req: NextRequest) {
const basicAuth = req.headers.get('authorization')
if (basicAuth) {
// do whatever checks you need here
const hasAccess = ...
if (hasAccess) {
// will render the specified page
return NextResponse.next()
}
}
// will not allow access
return new Response('No access', {
status: 401,
headers: {
'WWW-Authenticate': 'Basic realm="Secure Area"',
},
})
}
You can find more info in the documentation.
I am really new in shopify app development.
I have an allready a working app what i have created with next.JS (I have worked with node/express too)
I just would like to create a connection between my frontend and backend with a simple endpoint.
It means i send a get request and i receive something nonsense. The main goal would be that is the backend can communicate with the frontend.
I have created a git repo too.: https://github.com/akospaska/shopify-outofthebox
The app has been created with shopify-cli
In my pages folder there is an index.js file, where my frontend "lives".
I have created (or i think ) 2 differend endpoints.
pages/api/test endpoint: "/test"
server/server.js endpoint: "/test2"
When i call the endpoints i get an error.
I have read the documentation but it just makes me confused.
How should i authenticate between my backend and frontend exactly?
Thank you for your help Guys in advance.
The endpoints aren't pages, they are routes on your express app.
Here is a related question with answer:
Node backend communication between react frontend and node backend | Shopify related
Here is a checklist for you how to set up an endpoint (POST):
1.) Navigate to your index.js file in the /web directory
2.) Insert this code:
app.post("/api/test", async (req, res) => {
try {
res.status(201).send(response);
} catch (error) {
res.status(500).send(error.message);
}
});
}
app.post() sets up a route in your project.
3.) Navigate to your index.jsx file in /pages directory and insert this code (I set up a callback when a form submit button is clicked):
const handleSubmit = useCallback(
(body) => {
(async () => {
const parsedBody = body;
const response = await fetch("/api/test?shop=YOUR_SHOP_URL, {
method: "POST",
body: parsedBody
});
if (response.ok) {
console.log("Success");
}
})();
return { status: "success" };
},
[]
);
<Form onSubmit={handleSubmit}>
</Form>
it should call this API endpoint. So now you communicate with an API endpoint.
Maybe I could help you with my answer!
i want send request to an api but i have 404 erro and i have nothing in network
can you help me?
my code:
loginMethod() {
const config = {
userName: "test#gmail.com",
password: "1234test",
};
return new Promise((resolve) => {
ApiService.post("api/authentication/login", config)
.then(({ data }) => {
console.log(data);
resolve(data);
})
.catch(({ response }) => {
console.log(response);
});
});
},
and ApiService function:
post(resource, params) {
console.log(params);
const headers = {
"E-Access-Key": "bb08ce8",
};
return Vue.axios.post(`${resource}`, params, { headers: headers });
},
Based only on what I can see in your code, you are not telling axios the complete URL if I'm right about it, and you didn't declare it somewhere else do this:
axios.post('yourdomain.com/api/authentication/login',params)
or
axios({
url:'yourdomain.com/api/authentication/login',
method:post,
data:{}
})
or
in your main js file or any other file that you import axios (if you are sharing an instance of it globali):
axios({baseurl:'yourdomain.com'})
and then you don't need to write the complete url everywhere and just insert the part you need like you are doing now and axios will join that address with the baseurl,I hope it helps
I guess the URL "api/authentication/login" might be wrong and the correct one would be "/api/authentication/login" that starts with /.
404 error means the resource referred by the URL does not exist. It happens when the server has deleted the resource, or you requested a wrong URL accidentally, or any wrong ways (e.g. GET vs POST)
To make sure if you were requesting to the correct URL (and to find where you're requesting actually), open Google Chrome DevTools > Network panel. You might need reload.
The url api/xxx is relatively solved from the URL currently you are at. If you were at the page http://example.com/foo/bar, the requested URL becomes http://example.com/foo/bar/api/xxx. Starting with / means root so http://example.com/api/xxx.
This answer might help to understand the URL system: https://stackoverflow.com/a/21828923/3990900
"404" means your API Endpoint is not found. You need to declare the location of your API Endpoint exactly. For example: http://localhost:8080/api/authentication/login.
I am trying to send a POST request to an endpoint that takes a application/x-www-form-urlencoded Content-Type and a plain text string for the form data with the apollo-link-rest module and am having the hardest time.
In cURL form the request I want to make looks like this:
curl -X POST http://tld.com/search -d include_all=My%20Search%20Term
I have wrapped my main component in the graphql HOC from react-apollo like this.
export default graphql(gql`
mutation productSearch($input: string) {
search(input: $input) #rest(
path: "/search",
method: "post",
endpoint: "search",
bodySerializer: "search"
) {
total
}
}
`,
{
props: ({ mutate }) => ({
runSearch: (text: string) => {
if (mutate) {
mutate({
variables: {
input: `include_all=${encodeURIComponent(text)}`,
},
});
}
},
}),
})(SearchResults);
The search bodySerializer referenced in the query looks like this.
const searchSerializer = (data: any, headers: Headers) => {
headers.set('Content-Type', 'application/x-www-form-urlencoded');
return { body: data, headers };
};
And then have called the runSearch function like this in my component.
async componentDidMount() {
try {
const result = await this.props.runSearch(this.props.searchText);
} catch (error) {
// report error & show message
}
}
Now I realize I'm not doing anything with the results but there seems to be an unhandled promise rejection (that's what React Native is telling me with a yellow box warning) when running the search code. I'm examining the request with Reactotron as well and the request looks good, but it fails still. I'm wondering if I'm missing something with how I'm configuring apollo-link-rest or if there's a better way I can examine requests made from the Apollo client.
Any help here would be much appreciated. Thanks!
So it turns out that I had everything setup correctly above. Instead of it being an issue with react-apollo it was an issue with my Info.plist file. I hadn't enabled the ability of the iOS app to make HTTP requests. It was only allowing HTTPS. I fixed it with this entry in my Info.plist.
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>