I'm trying to add existing backend to a new react frontend. Every time I call the API from react i get,
Uncaught (in promise) API api3ceaf69c does not exist
Client side code
function getData() {
const apiName = "api3ceaf69c";
const path = "/users";
const myInit = {
headers: {},
};
return API.get(apiName, path, myInit);
}
(async function () {
const response = await getData();
console.log(JSON.stringify(response));
})();
index.js
import { Amplify, API } from "aws-amplify";
import awsExports from "./aws-exports";
Amplify.configure(awsExports);
API.configure(awsExports);
aws-exports.json
{
"aws_cloud_logic_custom": [
{
"name": "api3ceaf69c",
"endpoint": "https://xxxxxxx.execute-api.ap-south-1.amazonaws.com/dev",
"region": "ap-south-1"
}
]
}
"aws-amplify": "^4.3.27"
Error
Error screenshot
I went through multiple answers around the same issue but none of them are working for me.
Interestingly this exact same code was working a few days back until I had to rebuild my backend due to some changes.
I thought client code used aws-exports.js to decide if the API exists. Looks like you may have checked it already. Does the xxxxxxx API from your exports file show up in the API Gateway in AWS Console? Can you invoke it from the console?
I figured out the problem finally! Issue was at the place where I'm calling Amplify.configure(aws_exports).
For some reason aws exports was not getting initialized in index.js file so I moved it closer to where I am actually calling the api, i.e. getData() function. It started working post that.
Related
Hello everyone I am extremely new at the Next.js world.
I am using the getStaticProps() to make an API call and in order to make it little organized, i have created a separate page "git" under "pages" folder and here is my code:
function Git({ stars }) {
return <div>Next stars: {stars}</div>
}
export async function getStaticProps() {
const res = await fetch('https://api.github.com/repos/vercel/next.js')
const json = await res.json()
return { stars: json.stargazers_count }
}
export default Git
And i am trying to load the API data to the index.js file under the "pages" folder.
Inside the index.js file, i am using below to load the API data from the "Git" page
import fetch from "isomorphic-unfetch"
import Git from './Git'
And under the following
render () {
return (
<Git />
On the browser, i am not seeing the API data but i am seeing the HTML from the "Git" page
<div>Next stars: </div>
Is there any way if i can load the API data from different page to the index.js page?
However, if i directly access the page for example: http://0.0.0.0:3000/Git then i get the proper API data.
Issue
The issue is about the API data in the page "Git" is not getting passed to the main page "index.js" is there any way if i can pass the data from the "Git" to the "index.js"
I resolved it by putting the following code in the index.js file
const gitData = await Git.getInitialProps();
And that's where I want to print it out
<Git {...this.props.gitData}/>
I want to call an API in asyncData()
async asyncData({ $axios, params, store }) {
let itemUUID = params.item;
let item = await $axios.get("/item/" + itemUUID);
return {item};
}
Problem: Axios is still making the request on http://localhost:3000
if I do a console.log($axios.defaults.baseURL) the correct baseURL of my API is printed.
This also works if I use my store action & make the call by using this.$axios
I am using #nuxtjs/axios 5.13.1 with Nuxt 2.15.6 in SSR mode and configured it with the correct baseURL in the nuxt.config.js
Interestingly, if I edit my page content and a hot module reload is triggered, the correct URL is used. Maybe the question should be if Axios is triggered in the right time, on the server?
Edit: I checked the request that was made on HMR and this was triggered in the client.js.
If I call my store inside the created() hook the request gets executed successfully.
My nuxt.config.js:
publicRuntimeConfig: {
axios: {
baseURL: process.env.EXPRESS_SERVER_URL
}
},
privateRuntimeConfig: {
axios: {
baseURL: process.env.EXPRESS_SERVER_URL,
}
},
I'm not sure what is the NODE_TLS_REJECT_UNAUTHORIZED=0 thing doing but your frontend configuration (Nuxt) is working well so far.
Sorry if I cannot help on the Express part.
Maybe try to setup HTTPS locally on Nuxt: How to run NUXT (npm run dev) with HTTPS in localhost?
TLDR; This was not related at all - I forgot to set the auth token for my backend. At the time of axios init it's not present. $axios object doesn't have auth - backend fails.
On page load the nuxt function nuxtServerInit() is used to get the auth token out of the acces_token cookie.
I am using a plugin to initialize Axios - with the token from the store.
But of couse the token is not present at the time axios is initialized as nuxtServerInit is called after plugin init.
In my axios.js plugin I changed:
export default function({ app, error: nuxtError, store }) {
const token = const token = store.state.user.token;
app.$axios.setToken(token, "Bearer");
}
to;
export default function({ app, error: nuxtError, store }) {
const token = app.$cookies.get("access_token");
app.$axios.setToken(token, "Bearer");
}
Now the token is present & used for every request happening server-side.
I'm trying to write a basic local api for myself using Next.js, it is a timeline generator, and I am stuck at actually reading the file from the api folder.
What do I want in my local aplication:
1.A simple page where I can input an event, with a date and description
2.Open a list.json file somewhere and push that new event to that json file, writing on it.
What I am currently doing and where I am stuck:
I am aware we cant write on files on the client side, so I started looking at the api routes in next js to access the JSON file, but I cannot even manage to read it!
I have an api folder inside pages folder, and in this api folder I have two files: one is the list.json file, where I previously manually write some events with respective dates; and the other is getlist.js, with this code:
var fs = require('fs');
export default function getList(req, res) {
const rawList = fs.readFile('list.json');
var list = JSON.parse(rawList);
res.json(list);
}
Now on the pages folder I have a index.js file where I try to access this getlist.js api using getStaticProps(), like this:
import getlist from './api/getlist'
export async function getStaticProps(){
var list = getlist();
return {
props: {
list
}
}
}
I have tried using other stuff, like the fecth function, to get to getlist.js, but nothing I do seems to work.
Can anyone help me?
And since I'm already in here, how would I manage to get the input from the form I already have in my client side page and write it to that list.json file in my api folder?
There are two ways how you can read json in next.js:
Import inside getStaticProps [https://nextjs.org/docs/basic-features/data-fetching#getstaticprops-static-generation]
export async function getStaticProps(context){
const example = await import('./api/example.json');
return {props: {example: example.default}}
}
Import or read in handler function inside api folder [https://nextjs.org/docs/api-routes/introduction]:
const fs = require('fs');
export default async function handler (req, res) {
const example = await fs.readFile('./example.json');
return res.status(200).json({example});
}
In order to write *.json file you need to send request with value to the server api (handler from api folder that was mentioned before).
That's how the part to write json will look like:
const fs = require('fs');
export default async function handler(req, res) {
//...
if (req.method === 'POST'){
fs.writeFileSync('./example.json', JSON.stringify(req.body))
return res.status(200).json({});
}
//...
}
I am trying to hit an endpoint in my reactjs code using axios but the request is getting blocked and I am getting the following error in my console.
Please suggest how to overcome this
Below is my code
import * as React from 'react';
import axios from "axios"
export default function App()
{
return (
<>
<button onClick={fetchdata}>Click Me</button>
</>
)
}
function fetchdata()
{
const axios = require('axios');
// Make a request for a user with a given ID
return axios.get('https://randomuser.me/api')
.then(response => {
// handle success
console.log(response);
return response;
})
.catch(error => {
// handle error
console.log(error);
})
}
The reason you're getting this error is because https://randomuser.me expects request from secured origin using https protocol and localhost by default does not runs over https. If this is not satisfied it will be returned as a warning/error by your browser.
However, if you have generated React Project using create-react-app then you can add following script in your package.json:
"proxy": "https://randomuser.me"
Please refer document of Create React App for more details.
It's working fine, please check here
Codesandbox: https://codesandbox.io/s/muddy-dust-yvotv?file=/src/App.js
sometimes this error coming because you started any plugin/extention of cors in your browser
In my Saga test for my react native application (that does work correctly) I have added the following test that calls a function that perform a POST http call (doScan).
describe('Scan the product and register the scanning action', () => {
const it = sagaHelper(scanProductSaga(scanProductAction(item)));
it('logscan via ASL', (result) => {
expect(result).toEqual(cps(ASLogger.logScan, xxx));
return logScanResult;
});
it('should register the product', (result) => {
expect(result).toEqual(call(doScan, logScanResult));
});
});
Separate file:
const doScan = scanObj =>
toJSON(fetch('https://xxxx.xxxxxx.com/logger/scans', {
method: 'POST',
headers: new Headers(CONTENT_TYPE_HEADERS),
body: JSON.stringify(scanObj),
}));
Note: the fetch function is from 'react-native-interfaces.js' within the react-native library. The test fails and the error is caused by the following exception :
ReferenceError: fetch is not defined
at doScan (/Users/andy/WebstormProjects/ASAP/api/index.js:81:11)....
What can cause such issue? What the solution may be?
react-native has fetch default, but test environment on node.js does not have fetch.
You can import fetch like following at the top of test code.
const fetch = require('node-fetch')
The file react-native-interface.js only declare the type of fetch.
declare var fetch: any;
For some cases, in a universal application for both, client and server the maintainers have to use isomorphic-fetch module to their Node project because of Node does not contain Fetch API yet. For more information read this question and answer
But in this special case, hence, React Native, it is some different, Because, in the mobile device area, there is no V8, SpiderMonkey or Node. There is JavaScriptCore. So, for this new situation should be used react-native-fetch.
It is a little different, install it with below code:
npm install react-native-fetch
And then, use it like a JSX component:
import Fetch from 'react-native-fetch'
...
<Fetch
url="https://jsonplaceholder.typicode.com/posts/1"
retries={3}
timeout={3000}
onResponse={async (res) => {
const json = await res.json()
console.log(json)
}}
onError={console.error}
/>
It's so new, but lovely.