I am building a simple API using Dart Shelf. The GET requests work fine but I can't seem to be able to access the request body for a POST request.
import 'dart:io' show InternetAddress;
import 'package:shelf/shelf.dart' show Request, Response;
import 'package:shelf/shelf_io.dart' show serve;
import 'package:shelf_router/shelf_router.dart' show Router;
void main() async {
Router router = Router();
router.get('/', (Request request) {
return Response.ok('this is the base URL');
});
router.post('/accounts', (Request request) async{
final body = await request.readAsString();
print(body);
return Response.ok(body);
});
final server = await serve(
router,
InternetAddress.anyIPv4,
8080,
);
print('Serving at http://${server.address.host}:${server.port}');
}
When I make the request I get the 200 OK status code but where is the body data?
Related
I am trying to fetch a blob in the form of a media/gif and then immediately send it to my front-end. I need to first fetch it in my back-end (serverless function in Vercel) for security and caching purposes. When fetching the blob/image directly from the source URL in Postman and in my front-end everything works, but when first fetching it in my backend and then passing it to Postman and my front-end it does not work.
The code for my back-end:
export default async (_: NowRequest, response: NowResponse) => {
const res = await Axios.get(
"{BLOB_URL}"
);
response.setHeader("Content-Type", "media/gif");
return response.status(200).send(res.data);
};
What am I missing?
Solved it by adding the following:
export default async (_: NowRequest, response: NowResponse) => {
const res = await Axios.get(
"{BLOB_URL}",
{ responseType: "arraybuffer" } <--- ADDED THIS
);
response.setHeader("Content-Type", "media/gif");
return response.status(200).send(res.data);
};
I am quite new to vue and I am trying to send a request to my api using axios.
I build an interceptor which seems to work (logging is happening)
export default function setup() {
console.log('Http interceptor starting...')
Axios.interceptors.request.use((request) => {
const token = store.getters.token;
if (token) {
request.headers.Authorization = `Bearer ${token}`;
}
console.log(request);
return request
}, (err) => {
return Promise.reject(err);
});
}
If I check the console I can see the request including the token. If I check my network tab in the browser i can see the same request without the token. If I check the console of my api the token is null. Any Ideas?
Edit: If I use postman with the same request and the same token it is working as it shuld
I have an application where I want to avoid robots to try to use my socket.io endpoint.
My socket.io sits on top of express:
const app = require('express')();
app.use(blockRobots);
const io = require('socket.io')(app{path: '/socket'});
If I access this server to any path except /socket, the middleware is executed.
However, doing a (GET) request to /socket does not trigger the middleware.
Any ideas?
Without delving into the code, I assume that socket.io attaches a listener to the HTTP server that gets triggered before Express gets to handle the request at all.
You can use the allowRequest option for socket.io to reject unwanted requests:
const io = require('socket.io')(app, {
path: '/socket',
allowRequest: (req, callback) => {
if (CHECK_FOR_ROBOT) {
return callback(null, false);
} else {
return callback(null, true);
}
}
});
this is the fist time i've tried post method in dartLang.
ive used a simple rest api , where you have to post some string(text) and will get Json as response.
I've also Given right Username and password, yet the response I recieve Finally is {code: 401, error: Unauthorized}.
May I know Where I am goin wrong?? I've never worked with Rest api's post in DartLang.
Here is its simple documentation https://www.ibm.com/watson/developercloud/personality-insights/api/v3/curl.html?curl
import 'package:untitled1/untitled1.dart' as untitled1;
import 'package:http/http.dart' as http;
import 'dart:async';
import 'dart:convert';
void main() async {
Map hello;
hello= await getjson();
print(hello);
}
Future<Map> getjson() async {
String data;
data= """ Insert Random long text """;
var url = 'https://gateway.watsonplatform.net/personality-
insights/api/v3/profile?username=6cfcbb79-1801-4588-a1b3-
5c3ec101244f&password=YFM6h0rIFfzf';
http.Response response= await http.post(url, body: data, headers:
{"accept" : "application/json","Content-Type": "text/plain"},);
return json.decode(response.body);
}
The Watson reference that you provide shows an example with curl -u. curl defaults to Basic authentication when -u is provided without a specific authentication method (e.g. digest). So, adding the username and password to the url is not the same.
Dart's http client supports basic authentication, but will require an additional round-trip to the server, so it's often simpler to send the credentials with every request. The following code gets you past the 401 error.
import 'dart:convert';
import 'package:http/http.dart' as http;
main() async {
http.Response r = await http.post(
'https://gateway.watsonplatform.net/personality-insights/api/v3/profile',
body: 'some random string',
headers: {
'Accept': 'application/json',
'Authorization': basicAuthorizationHeader(
'6cfcbb79-1801-4588-a1b3-5c3ec101244f',
'YFM6h0rIFfzf',
)
},
);
print(r.statusCode);
print(r.body);
}
String basicAuthorizationHeader(String username, String password) {
return 'Basic ' + base64Encode(utf8.encode('$username:$password'));
}
I'm new to Vuejs 2, currently using vue-resource to retrieve data from the server. However, I would need a token passed in the request header at the same time in order to retrieve the data from the server.
So the problem is, I am unable to retrieve data because the token is not passed into the request header, using vue-resource.
Here is the method that uses the vue-resource's interceptor (to pass in the token) to intercept the GET request:
test () {
this.$http.interceptors.push((request) => {
var accessToken = window.localStorage.getItem('access_token')
request.headers.set('x-access-token', accessToken)
return request
})
this.$http.get(staffUrl)
.then(response => {
console.log(response)
}, (response) => {
console.log(response)
})
}
Documentation for vue-resource, HTTP: https://github.com/pagekit/vue-resource/blob/develop/docs/http.md
When I try to GET the data, i end up with an error 403 (forbidden) and after checking the request headers in the dev tools, I also could not find the token in the request headers.
Please tell me where I went wrong because I'm really new to this so i appreciate any help! Thank you!
Setting interceptors inside the component using $http doesn't work, or at least it doesn't in my testing. If you examine/log this.$http.interceptors right after your push in the test method, you'll note that the interceptor was not added.
If you add the interceptor before you instantiate your Vue, however, the interceptor is added properly and the header will be added to the request.
Vue.http.interceptors.push((request, next) => {
var accessToken = "xyxyxyx"
request.headers.set('x-access-token', accessToken)
next()
})
new Vue({...})
Here is the test code I was using.
Also note, if you are using a version prior to 1.4, you should always call the next method that is passed to the interceptor. This does not appear to be necessary post version 1.4.
please go through this code
import vueResource from "vue-resource";
import { LocalStorage } from 'quasar'
export default ({
app,
router,
Vue
}) => {
Vue.use(vueResource);
const apiHost = "http://192.168.4.205:8091/";
Vue.http.options.root = apiHost;
Vue.http.headers.common["content-type"] = "application/json";
Vue.http.headers.common["Authorization"] = "Bearer " + LocalStorage.get.item("a_t");
Vue.http.interceptors.push(function(request, next) {
console.log("interceptors", request);
next(function(response) {
});
});
}