I wanted to receive data to my site on React through the API.I did everything as stated in the documentation, performed the installation of npm install --save woocommerce-api, created the object with parameters as in the documentation http://woocommerce.github.io/woocommerce-rest-api-docs/?javascript#pagination
import React, { Component } from 'react';
import '../App.css';
import WooCommerceAPI from 'woocommerce-api';
class Goods extends Component {
WooCommerce = new WooCommerceAPI({
url: 'http://portland.com/wp/', // Your store URL
consumerKey: '**KEY**', // Your consumer key
consumerSecret: '**KEY**', // Your consumer secret
wpAPI: true, // Enable the WP REST API integration
version: 'wc/v2' // WooCommerce WP REST API version
});
render() {
return(
<div className="GoodsMain">
<div className="Goods">
<img src="/images/photo.png" alt="appletv"/><br/>
<div className="TextAlign">
<span className="NameOfGood">{WooCommerce.get('products/1').name}</span><br/>
<span className="StyleOfGood">black</span><br/>
<span className="PriceOfGood">$49.99</span>
</div>
</div>
</div>
);
}
}
export default Goods;
But I get Line 20: 'WooCommerce' is not defined no-undef
Can u help me integrate correctly API in my site?
I Think you have to use the oauth authentication for getting the data from the woo-commerce rest api because your wordpress is on the server where there is no ssl certificate.
Try this way:
1). Use axios library (https://alligator.io/react/axios-react/) to call the WooCommerce Rest API.
2). To simplify the authentication process, make sure you enable SSL on your Wordpress hosting (I tried authenticate on the non SSL, it appears the process was not that easy, compared the SSL one).
3). Follow the steps from this link to generate the WooCommerce Rest API key
https://woocommerce.github.io/woocommerce-rest-api-docs/?javascript#authentication
4). Once everything setup, test retrieve list of products using Postman (https://www.getpostman.com/).
[GET]
https://{{host}}/{{wordpressFolder}}/wp-json/wc/v2/products/
[HEADER]
// Inside your React code, do this:
const basicToken = btoa(PRODUCTS_CONSUMER_KEY+':'+PRODUCTS_CONSUMER_SECRET)
Authorization: Basic ${basicToken}
Related
I'm trying to understand the differences between Next.js 13 server components and client components, and I have a few questions:
If the server component doesn't have the ability to access hooks, what is the benefit of using it, and how can users interact with it?(state, reactivity)
Are both client components and server components SEO-friendly, or is one better for SEO than the other?
Can we hide API endpoints with client components like we can with server components?
A sample situation:
app/abc/page.tsx
import { useState } from "react";
export default function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}
Error:
"useState" is not allowed in Server Components.ts(71001)
All Next components have ability to access hooks. But for example useEffect will be executed only in client side.
Server component better for SEO. Because for search engines SSR page looks like static HTML already generated on server.
Hide like SSR - no. Because components rendered in server side and all method required for render called on server. But user requests will be on client side and with SSR and with CSR. But Next offers a built-in proxy function
Yes, with app dir exists some problems.
This approach allows you to make SSR component without getServerSide props and with some others new features. But this is beta and if for you it creates some problem, dont use app dir, use getServerSideProps
I have a two basic next apps that uses next-auth for its authentication along with keycloak provider.
i've been trying to use the feature of SSO (single sign on) that keyckoak provides, so i have a website running on http://localhost:3000/ and another one on http://localhost:3001/, and everytime i try to login using the second app, it redirects me to localhost 3000, not localhost 3001, which is a weird behavior, let me show you some code.
api/auth/[...nextauth].ts
(note: i'm using same realm and clientId for both apps)
import NextAuth from "next-auth/next";
import KeycloackProvider from "next-auth/providers/keycloak";
export default NextAuth({
debug: true,
providers: [
KeycloackProvider({
clientId: "react-client-1",
clientSecret: "react-auth",
issuer: "http://localhost:8080/realms/react-auth",
enter image description here }),
],
});
Function to sign in
here, the callbackUrl just doesn't work, no matter what i put there, it's just not going to redirect me to that url
const handleKeycloackSignIn = (): void => {
signIn("keycloak", {
callbackUrl: "http://localhost:3001/",
});
};
next-auth cookies for redirecting on localhost:3001
photo #1
Keycloack config
photo #2
What could be the reason for always redirecting to localhost:3000 ? is it some next-auth config that i'm missing or, maybe is related to keycloak ?
How can i redirect to wherever i want after a successful login/logout
I've tried hardcore google search around this topic, nothing really related to my specific issue.
You need to add some variables that next-auth need to your .env file, something like this.
NEXTAUTH_URL=http://localhost:3000/
NEXTAUTH_SECRET=PRUEBA
this provides the url to redirect and a secret to your jwt token
I need some help to get me started with NextAuth.js
Following this guide I am trying to add Google authentication with existing Next.js app. I registered an app via Firebase and got GOOGLE_ID and GOOGLE_SECRET which I set in the app. Here is my [...nextauth].js:
import NextAuth from "next-auth";
import GoogleProvider from "next-auth/providers/google";
export const authOptions = {
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_ID,
clientSecret: process.env.GOOGLE_SECRET,
}),
// ...add more providers here
],
};
export default NextAuth(authOptions);
.env.local file:
GOOGLE_ID=xxx
GOOGLE_SECRET=xxx
NEXTAUTH_URL=http://localhost:3000
Then in the component I import:
import { signIn, signOut, useSession } from "next-auth/react";
Then I call it like this:
<div className="link" onClick={signIn}>
<p>Hello Alex Smith</p>
<p className="font-extrabold md:text-sm">Account & Lists</p>
</div>
Then weird stuff begins. Then I click on the div, I get to see button: Login With Google and URL is:http://localhost:3000/api/auth/signin?callbackUrl=http%3A%2F%2Flocalhost%3A3000%2F
When I click on it, I get Internal Server Error and URL is:http://localhost:3000/api/auth/signin/google
Also in terminal I see: ReferenceError: ReadableStream is not defined popping up. Don't know if that is relevant.
Strangely, in Google console I see no trace of app registered in Firebase.
I tried creating OAuth client manually and getting different set of credentials, switching Google account - to no avail.
I always hit that error and cannot go further. They say NextAuth is super easy to integrate, however...
Found the cause was do do with version of Node.
Updated it to the latest version and that fixed the issue.
Now can can log in.
been playing around with a simple blog built with JSONPlaceholder and Nuxt.js
Everything seems fine, I've got an archive and single blog posts working fine but when deployed on Netlify I can see that the browser is still doing API calls to JSONPlaceholder even though all the pages are built static and I can see they already have the content within the HTML.
I used the routes method within generate in the nuxt config to create the 100 html files based upon the JSONPlaceholder /posts results.
Here's the Netlify link: REMOVED.
And a public repo: https://bitbucket.org/oneupstudio/api-test/src/master/
Anything I've missed?
Nuxt.js doesn't support 'full static generation' yet, check this RFC.
For now, you can use this module in order to make your JSON requests static.
Nuxt currenty supports proper static generation of websites. Although one has to be aware of payload param in asyncData. So if payload is present that indicates that static generator is at work and no api calls should be made in this case:
async asyncData ({ params, error, payload }) {
if (payload) return { user: payload }
else return { user: await backend.fetchUser(params.id) }
}
Read more on this here.
RFC mentioned by #DreadMinder will further improve on this, but you can already do full static websites with Nuxt.
I was using "angular-in-memory-web-api" to mock my REST web api, however now I am have started writing the actual web api and I want to replace the "angular-in-memory-web-api" step by step.
Example:
I have written following asp.net web api
/api/values
however when I issue http.get() request using above api url angular tries to serve it using "angular-in-memory-web-api", however in this case I want to bypass "angular-in-memory-web-api" so that request is entertained by my actual web api controller.
you can set passThruUnknownUrl to forward to real backend for un-matching endpoints
e.g.,
InMemoryWebApiModule.forRoot(InMemoryDataService, {
passThruUnknownUrl: true
}),
You can try by removing InMemoryWebApiModule.forRoot(InMemoryDataService) from your app.module. If you have done so already, showing some code would be helpful.
Also, consider using Postman to verify your new service
in app.module.ts
import { HttpClientInMemoryWebApiModule } from 'angular-in-memory-web-api';
import { InMemoryDataService } from './my-module/services/in-memory-data.service';
in app.module.ts imports array
HttpClientInMemoryWebApiModule.forRoot(InMemoryDataService, { dataEncapsulation: false, passThruUnknownUrl: true })
passThruUnknownUrl related doc