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>
Related
I'm moving my existing project written on Express.js to Nest.js and one of the most pressing problem is to serve static html page for changing user's password. I've been looking for any answer for a couple of days, unsuccessfully. My implementation on Express.js works perfectly, here it is:
resetPass.use(express.static(__dirname + "/reset_pass_page"));
resetPass.get("/:id", async (req, res) => {
try {
// here I check ID which is JWT and if everything is OK I send the form:
res.status(200).sendFile(__dirname + "/reset_pass_page/index.html");
}
And now I'm trying to reach the same outcome using Nest.js. I got one single module for resetting password and sending links to user's email. Here is the controller:
#Controller('users/resetpass')
export class ResetPassController {
constructor(private readonly resetPassService: ResetPassService) { }
// here is others routes for getting reset link on user's email and etc...
// in this part I'm sending the form:
#Get("requestform/:id")
sendResetPasswordForm(#Param("id") resetToken: string) {
return this.resetPassService.sendResetPasswordForm(resetToken)
}
}
And what should I do in the service in my case?
async sendResetPasswordForm(resetToken: string) {
try {
// checking resetToken and if it's OK send form like:
res.sendFile(__dirname + "/reset_pass_page/index.html");
What method should i use in that case?
}
}
I've already tried to use ServeStaticModule in my reset pass modle, but I can't make it work properly with dynamic routes. I've tried this config:
ServeStaticModule.forRoot({
rootPath: join(__dirname, '../../../static/resetpass'),
renderPath: /(\/users\/resetpass\/requestform\/)([\w-]*\.[\w-]*\.[\w-]*)/g,
}),
I can make it work for routes without ID, like users/resetpass/, but I need to these page be available only for routes like users/resetpass/:id.
I'm looking forward for any help and advice. Thanks!
Similarly to what you did in Express.js:
res.status(200).sendFile(__dirname + "/reset_pass_page/index.html");
You can also use .sendFile in Nest.js
#Get("requestform/:id")
sendResetPasswordForm(#Req() req: Request, #Res() res: Response) {
const resetTokenPath = this.resetPassService.sendResetPasswordForm(pararms.id)
res.sendFile(join(__dirname, resetTokenPath, '/reset_pass_page/index.html'));
}
You have to add a couple of decorators and types from Express:
import { Controller, Get, Res, Req } from '#nestjs/common';
import { Response, Request } from 'express';
I have a web application built using NuxtJS/Vuejs within that I have a field where user can provide the URL and my application should make a GET request to that URL and obtain the data. Mostly the URL is related to GitHub from where it should fetch XML/JSON the data.
When I provide a certainly URL in browser/Postman then the redirection happens and data from the redirected URL is loaded. I want to achieve the same in my code but it's not happening and I get the error:
index.js:52 GET {{URL}} net::ERR_FAILED 302
But these URL works perfectly in browser and in Postman without any issue. Following is my code where I am making the request using Vuejs Fetch:
fetch(inputURL, {
method: 'GET'
})
.then((response) => {
console.log('RESPONSE')
console.log(response)
})
.catch((error) => {
console.log('ERROR')
console.log(error.response)
})
Using the Axios:
axios
.get(inputURL)
.then((response) => {
console.log("RESPONSE");
console.log(response);
})
.catch((error) => {
console.log("ERROR");
console.log(error);
})
I tried setting various header, I tried using axios etc but nothing seems to work for me. Can someone please explain to me what am I doing wrong and how to fix this issue? Any help or workaround would be really appreciated.
First of all, the 'Access-Control-Allow-Origin' header is something that should be set up on the server side, not on the client making the call. This header will come from the server to tell the browser to accept that response.
The reason why your code works from postman/browser is because you're not under the CORS rules when you request it like that.
One way around it, would be to make a call to your backend and tell the backend to call GET the data from the URL provided and then return it to your front-end.
Example:
//call_url.php
<?php
$url = $_GET['url'];
$response = file_get_contents($url);
echo $response
?>
//vue.js component
<input type="text" v-model="url"></input>
<button type="button" #click="callUrl">call me</button>
...
methods: {
callUrl() {
axios.get('call_url.php?url=' + encodeURIComponent(this.url))
.then(response => {
//...do something
}
}
}
As mentioned in another answer it's not possible for any library including Fetch and Axios to make requests and obtain the Data due to various security policies. Hence, I created a method in my Spring boot application that will obtain the data from URL and I make a request to my Spring boot using Axios.
import axios from 'axios'
axios.post('/urlDataReader', inputURL)
.then((response) => {
console.log(response)
})
.catch((error) => {
console.log(error)
})
Spring boot app:
//Method to read the data from user-provided URL
#PostMapping(value = "/urlDataReader", produces = "text/plain")
public String urlDataReader(#RequestBody String inputURL) {
final String result = new RestTemplate().getForObject(inputURL, String.class);
return result;
}
Im looking to use $auth inside my Nuxt project, specially inside an axios plugin.
Here is my code:
plugins/api.js
export default function ({ $axios }, inject) {
const api = $axios.create({
headers: {
common: {
Accept: 'text/plain, */*',
},
},
})
// Set baseURL to something different
api.setBaseURL('http://localhost:4100/')
// Inject to context as $api
inject('api', api)
}
Now the problem comes when I try to use $auth from #nuxtjs/auth-next package.
As stated in the docs:
This module globally injects $auth instance, meaning that you can
access it anywhere using this.$auth. For plugins, asyncData, fetch,
nuxtServerInit and Middleware, you can access it from context.$auth.
I tried the following:
This results in $auth being undefined
export default function ({ $axios, $auth }, inject) {
This one was near
export default function ({ $axios, app }, inject) {
console.log(app) //This one logs $auth in the object logged
console.log(app.$auth) // I don't understand why but this one returns undefined
My main goal here is to make use of this.$auth.strategy.token.get()and pass it (if the token exists of course) to the headers of every request made using this.$api
I have been looking for similar questions and answers but none has helped me to solve this, I could just add the token every time I write this.$api but that would increase the code unnecessarily.
Thanks in advance to all the people for your time and help.
EDIT:
Okay, now I made a test. and the next code is actually logging the $auth object correctly, it seems some time is needed to make it work but now Im afraid that using setTimeout could cause an error because I can't know exactly how much time is needed for $auth to be available.
export default function ({ $axios, app }, inject) {
setTimeout(() => {
console.log('After timeout', app.$auth)
}, 50)
EDIT 2:
So now I have made more tests, and using 0 milliseconds instead of 50 works too, so I will use setTimeout with 0 milliseconds for now, I hope anyone find a better solution or explain why $auth is not available before using setTimeout so I can decide what to do with my code.
EDIT 3:
After trying to wrap all my previous code inside setTimeout I noticed that the code fails, so that isn't a solution.
I have found a solution so I will post it so that every person that could have the same problem in the future can solve it.
It turns out that I could easily solve it using interceptors.
export default function ({ $axios, app }, inject) {
// At this point app.$auth is undefined. (Unless you use setTimeout but that is not a solution)
//Create axios instance
const api = $axios.create({
headers: {
common: {
Accept: 'application/json', //accept json
},
},
})
// Here is the magic, onRequest is an interceptor, so every request made will go trough this, and then we try to access app.$auth inside it, it is defined
api.onRequest((config) => {
// Here we check if user is logged in
if (app.$auth.loggedIn) {
// If the user is logged in we can now get the token, we get something like `Bearer yourTokenJ9F0JFODJ` but we only need the string without the word **Bearer**, So we split the string using the space as a separator and we access the second position of the array **[1]**
const token = app.$auth.strategy.token.get().split(' ')[1]
api.setToken(token, 'Bearer') // Here we specify the token and now it works!!
}
})
// Set baseURL to something different
api.setBaseURL('http://localhost:4100/')
// Inject to context as $api
inject('api', api)
}
Also Nuxt Auth itself has provided a solution for this issue:
https://auth.nuxtjs.org/recipes/extend/
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) }
I'm working on a Podio integration as a Slack bot.
I'm starting to use it just for use for my company to test it, then I could share it with everybody.
I've used the podio-js platform with Node JS, and started locally with a "web app" by starting from this example: https://github.com/podio/podio-js/tree/master/examples/password_auth
I need to do a post request, so I maintained all the code of the example in order to log in with user and password. The original code worked, then I changed the code to make a post request, in particular I change the lines of index.js into this:
router.get('/user', function(req, res) {
podio.isAuthenticated().then(function () {
var requestData = { "title": "sample_value" };
return podio.request('POST', '/item/app/15490175', requestData);
})
.then(function(responseData) {
res.render('user', { data: responseData });
})
.catch(function () {
res.send(401);
});
});
But in the end is giving a "Unauthorized" response.
It seems like the password auth doesn't let to make POST request to add new items! Is that possible?
I've already read all the documentation but I'm not able to explain why and how I can solve this.
Regards