I am building website using Gatsby and I am fetching some data from my backend. I want to set set global baseUrl for Axios. Normally I will do something like this:
import axios from "axios";
axios.defaults.baseURL = "API_ADDRESS";
But where should I put this in Gatsby to make it global?
in case someone else comes here, the suggestion of mohammed agboola is not accurate, using onInitialClientRender the base url will change to client side url when you refresh the page, in the same file gatsby-browser.js you should be using onClientEntry instead of onInitialClientRender :
export function onClientEntry() {
axios.defaults.baseURL = "YOUR_BASE_URL"
}
Create a gatsby-browser.js file in the root folder of your project, if you don't have one.
and use the lines of code below:
const axios = require("axios").default
exports.onInitialClientRender = () => {
axios.defaults.baseURL = "YOUR_BASE_URL_HERE"
}
The above lines of code set axios baseURL when Gatsby App is rendered to the browser. Hope this answers your question.
Related
First of all, I have found out what's wrong with my python code, but I really want some one to tell me how it popped out because I'm just a noob amateur.
I tried to post my album collected on my wordpress by using my python script as usual, but I got an unexpected throw-out when it start to image upload. My img upload function just like this:
def restImgUL(imgPath,imgName,token):
url='http://www.rainloongmusic.com/wp-json/wp/v2/media/'
file_extension = os.path.splitext(imgPath)[-1]
img = open(imgPath,'rb')
imgName = imgName.replace(";","")
_json = {
"title":imgName,
'caption': imgName,
"alt_text":imgName,
"description":imgName,
"status":"publish"
}
image_name = f"{imgName}{file_extension}"
headers = { 'Content-Type': '','Content-Disposition' : 'attachment; filename=%s'%image_name.encode("utf-8").decode("latin1"),"Authorization":"Bearer %s"%token}
res = requests.post(url=url,data=img,headers=headers,json=_json)
rrr = res.json()
if "id" in rrr:
return rrr["id"]
else:
print(rrr)
sys.exit()
The wrong response is an array include items in my first page of media library. I found some clues in rest api handbooks. If I attempt to GET /wp/v2/media, response will be like what I've recieved. But I use POST type request in my python code, I don't really understand what happened there. I have no choice but to try some other methods to bypass this problem. I tried to make a new endpoint and write something like this:
add_action( 'rest_api_init', function () {
register_rest_route( 'rlra/v1', '/media', array(
'methods' => 'POST',
'callback' => 'cmupload',
) );
} );
function cmupload(){
return "This is a test!!!"
}
However, I got rest_no_route when I POST to it. I changed the methods to GET eventually, and got the right text from my server. I think maybe something changed my POST request into a GET one? I tried to figure out with Charles, and found my connection with 302 permanent redirect. So I check my request link and change http into https, everything works.
So, could anyone tell me why a 302 redirect will change my POST request into GET, I've been worn-out due to the lost letter "s" in these days.
i can navigate to
https://www.facebook.com/plugins/likebox.php?id=20531316728 via my browser
but cant use jQ $.get , (not working with the specific url)
url='https://www.facebook.com/plugins/likebox.php?id=20531316728&width=292&height=258&colorscheme=dark&show_faces=true&border_color&stream=false&header=false';
$.get(url, function(data){alert(data);} );
can i use any method to fetch the url (js is preferred ) ? any idea?
Simple, You cannot make cross domain ajax calls.
There are 2 options:
1) Try with JSONP Read - http://api.jquery.com/jQuery.getJSON/
2) Make an ajax call to your site URL where you can use CURL to facebook URL to get the data.
we could not access the cross domain data with ajax request
$.get("your_cross_domain_url",function(response)
{
});
So, you have to use a local file to accessing the cross domain data.
var content="your_url";
var urlRegex = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
// Filtering URL from the content using regular expressions
var url= content.match(urlRegex);
if(url.length>0)
{
// Getting cross domain data
$.get("urlget.php?url="+url,function(response)
{
// do your stuff
});
and the urlget.php file should be like this
<?php
if($_GET['url'])
{
$url=$_GET['url'];
echo file_get_contents($url);//loading the URL data.
}
?>
I'm trying to create a link in a Liferay template using Velocity.
My code is the following, based on several examples on the net:
#set ($plid = $getterUtil.getLong($request.get('theme-display').get('plid')))
#set ($u = $portletURLFactory.create($request,"1",$plid,"RENDER_PHASE"))
$u.setParameter("struts_action","/asset_publisher/applyForJob");
yyy
I get the plid value, but my URL will be just ending with $u, it seems that the $portletURLFactory.create() method is not properly interpreted.
Any ideas? Thank you!
Are you trying to do this inside Web Content Template? In that case it will not work because you do not have access to the real http request object. You need to create this link using javascript instead. Here is a code snippet.
<script type="text/javascript">
function createURL() {
AUI().ready('liferay-portlet-url', function(A) {
var renderURL = Liferay.PortletURL.createRenderURL();
renderURL.setParameter("struts_action","/asset_publisher/applyForJob");
renderURL.setPortletId("1");
renderURL.setPortletMode("view");
renderURL.setWindowState("normal");
window.location = renderURL.toString();
});
}
</script>
Go
On the system I am working on right now, I have had to try to tame ember-data a bit about how it does its REST request. The way that ember-data by default figures the URL for a certain request for a model is just not gonna cut it with the backend I am using.
What I need is, to get ember-data to use the same URL that ember is loading, but with a '?json' suffix. That is, if ember switches page to my band page, and the url is /bands, I want ember-data to request /bands?json for the data it needs, not whatever it figures from the name of the model. One could say, that I wanted the URL to be calculated from the path of the loading route, instead of from the name of the model being used.
I have tried by subclassing DS.RESTAdapter{} and see if I could get the buildURL method to do this, but I can't figure out how to get the URL ember is gonna load. The buildURL method is called before ember changes the location, so I can't use document.location.href or something. I can imagine I will need a way to ask ember what it is now loading, and what the URL is.
Any ideas of how to do this?
UPDATE
There hasn't been any satisfying solutions, so I decided to just do it the dirty way. This is it:
App.RouterSignature = [
['index', '/', '/index_models'],
['bands', '/bands', '/band_models'],
['band', '/band/:band_slug', '/band_model']
];
App.Router.map(function() {
for (var i = 0; i < App.RouterSignature.length; i++) {
var route = App.RouterSignature[i];
this.resource(route[0], {path: route[1]});
}
});
App.CustomAdapter = DS.RESTAdapter.extend({
buildURL: function(record, suffix) {
var url,
suffix = '?json',
needle = this._super(record);
for (var i = 0; i < App.RouterSignature.length && !url; i++) {
var route = App.RouterSignature[i];
if (route[2] == needle)
url = route[1];
}
return url + suffix;
}
});
Now App.Routes and DS.RESTAdapter.buildURL are based off the same data. The first two values in the App.RouterSignature list is just the name of the route, the path of the route. The third value is what DS.RESTAdapter.buildURL by default guesses should be the url. My custom adapter then takes that guess, matches it with one of the items in the App.RouterSignature list and then takes the second value from that item - the routes path.
Now the requests that ember-data makes is to the same url as the routes path.
You can try to setup your Adapter like so:
App.Adapter = DS.RESTAdapter.extend({
...
buildURL: function(record, suffix){
return this._super(record, suffix) + "?json";
}
});
App.Store = DS.Store.extend({
...
adapter: App.Adapter.create();
...
});
See here for more info on the RESTAdapter buildURL method.
Hope it helps
I have a Controller action and sending a mail in it with something like:
mailService.sendMail {
...
g.render(template: "mailtemplate")
}
in this template file is called _mailtemplate.gsp I use
linktext
But the output is http://action ... that's it! I would expect to have http://www.example.com/action. If I use the same createLink tag in a gsp which is not a template it's working (by the way, email is working fine and all the other stuff in this template is rendered well).
Have you any suggestions on that?
Probably you need absolute link:
linktext
Btw, you can also use ${} syntax there, like:
linktext
QUOTE: I must specify a serverURL in config file, but I want it dynamically
You can probably do as such:
config.groovy:
environments {
development {
grails.serverURL = "http://localhost:8080"
}
production {
grails.serverURL = "http://www.mywebsite.com"
}
}
Then in your service sending the email:
import org.codehaus.groovy.grails.commons.ConfigurationHolder
def baseURL = ConfigurationHolder.config.grails.serverURL
mailService.sendMail {
...
g.render(template: "mailtemplate", model:['baseURL':baseURL])
}
And at last in your link:
linktext
I hope this helps